嗯,這是一個電影會見到的情節吧…
方法很簡單,就是 ransomNote 的每個字符出現次數要比 magazine 的少或等於。
Python
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: for c in set(ransomNote): if ransomNote.count(c) > magazine.count(c): return False return TrueC#
public class Solution { public bool CanConstruct(string ransomNote, string magazine) { var charSet = new HashSet(ransomNote); foreach(var c in charSet) { if(ransomNote.Count(p => p == c ) > magazine.Count(p => p == c )) return false; } return true; } }