Leetcode題解 Python & C#:五月挑戰DAY3 Ransom Note

給兩個字串:ransomNote、magazine,問 ransomNote 是否能從 magazine 裡面的宇符組成。

嗯,這是一個電影會見到的情節吧…

方法很簡單,就是 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 True

C#

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;
}
}