Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Note:
You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
我的想法是用map记录两边的字母表的每一个字母的个数,然后判断ransomNote里面字母肯定都要包含在magazine里面,而且个数要比它少。
public boolean canConstruct(String ransomNote, String magazine) {
Map<Character, Integer> mapRan = new HashMap<Character, Integer>();
Map<Character, Integer> mapMag = new HashMap<Character, Integer>();
for (int i = 0; i < ransomNote.length(); i++)
if (!mapRan.containsKey(ransomNote.charAt(i)))
mapRan.put(ransomNote.charAt(i), 1);
else
mapRan.put(ransomNote.charAt(i),
mapRan.get(ransomNote.charAt(i)) + 1);
for (int i = 0; i < magazine.length(); i++)
if (!mapMag.containsKey(magazine.charAt(i)))
mapMag.put(magazine.charAt(i), 1);
else
mapMag.put(magazine.charAt(i),
mapMag.get(magazine.charAt(i)) + 1);
for (Character c : mapRan.keySet()) {
if (!mapMag.containsKey(c) || mapRan.get(c) > mapMag.get(c))
return false;
}
return true;
}
这是LeetCode Discuss中的最热代码,它的原理就是列出了magazine的字母表,然后算出了出现个数,然后遍历ransomNote,保证有足够的字母可用,代码非常清晰。
public boolean canConstruct(String ransomNote, String magazine) {
int[] arr = new int[26];
for (int i = 0; i < magazine.length(); i++) {
arr[magazine.charAt(i) - 'a']++;
}
for (int i = 0; i < ransomNote.length(); i++) {
if(--arr[ransomNote.charAt(i)-'a'] < 0) {
return false;
}
}
return true;
}