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.
給予你任意的贖身訊息字串和另一個字串包含所有從雜誌上截下來的字母,寫一個程式,如果贖身訊息可以從雜誌構成,回傳 true ;否則回傳 false。
每個從雜誌截下來的字母都只能使用一次。
提示:
你可以假設兩個字串都只包含小寫英文字母。
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char, int> hash;
for(int i = 0; i < magazine.length(); i++)
{
hash[magazine[i]]++;
}
for(int i = 0; i < ransomNote.length(); i++)
{
if(hash[ransomNote[i]] > 0)
hash[ransomNote[i]]--;
else
return false;
}
return true;
}
};
LeetCode
C++