Java:
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] letter = new int[26];
for(char c: magazine.toCharArray()) letter[c - 'a']++;
for(char c: ransomNote.toCharArray()){
if(--letter[c - 'a'] < 0) return false;
}
return true;
}
}
Python:
class Solution:
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
#Counter类的目的是用来跟踪值出现的次数。它是一个无序的容器类型,以字典的键值对形式存储,其中元素作为key,其计数作为value。计数值可以是任意的Interger(包括0和负数)。
return not collections.Counter(ransomNote) - collections.Counter(magazine)