题目
Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.
Notes
- Only lower case letters will be used (a-z). No punctuation or digits will be included.
- Performance needs to be considered
Input strings s1 and s2 are null terminated.
Examples
scramble('rkqodlw', 'world') ==> True
scramble('cedewaraaossoqqyt', 'codewars') ==> True
scramble('katas', 'steak') ==> False
代码
using System;
using System.Linq;
public class Scramblies
{
public static bool Scramble(string str1, string str2)
{
var list1=str1.ToList();
var list2=str2.ToList();
foreach(char c in list2){
if(!list1.Remove(c)) return false;
}// your code
return true;
}
}
解题思路
本题难度在于解题的思路。我自己其实想不出来怎么写。
codewars里最聪明解法是用linq,一行搞定。
return str2.All(x=>str1.Count(y=>y==x)>=str2.Count(y=>y==x));
男朋友用的是remove。