Given two strings ransomNote
and magazine
, return true
if ransomNote
can be constructed by using the letters from magazine
and false
otherwise.
Each letter in magazine
can only be used once in ransomNote
.
Example 1:
Input: ransomNote = "a", magazine = "b" Output: false
Example 2:
Input: ransomNote = "aa", magazine = "ab" Output: false
Example 3:
Input: ransomNote = "aa", magazine = "aab" Output: true
Constraints:
1 <= ransomNote.length, magazine.length <= 105
ransomNote
andmagazine
consist of lowercase English letters.
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char,int>map;
for(auto x:magazine){
map[x]++;
}
for(auto x:ransomNote){
map[x]--;
}
for(auto x:ransomNote){
if(map[x]<0){
return false;
}
}
return true;
}
};
注意:
1.unordered_map<char,int>map;不是unordered_map<char,char>map
2.应该先遍历magazine,再遍历ransomNote
3.是map[x]<0才是false,因为可能magazine中出现的字母频率比ransomNote高,此时也是可以由magazine构成的