描述
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.
You may assume that both strings contain only lowercase letters.
您在真实的面试中是否遇到过这个题?
是
样例
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
无难度题,用关联容器即可
class Solution {
public:
/**
* @param ransomNote: a string
* @param magazine: a string
* @return: whether the ransom note can be constructed from the magazines
*/
bool canConstruct(string &ransomNote, string &magazine) {
// Write your code here
unordered_map<char,int> mag_map;
for(int i=0;i<magazine.length();i++) mag_map[magazine[i]]++;
for(int i=0;i<ransomNote.length();i++){
if(mag_map[ransomNote[i]]>0)
mag_map[ransomNote[i]]--;
else return false;
}
return true;
}
};