问题描述:
iven 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.
示例:canConstruct("a", "b") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true问题分析:
可以利用hashtable求解,将magazine中出现的字母次数记录下来,然后与ransomNote中出现的次数比较,若ransomNote出现某个字母出现次数大于magazine,则返回false。
过程详见代码:
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
vector<int> mapping(256,0);
for(int i = 0; i < magazine.length(); i++)
{
mapping[magazine[i]]++;
}
for(int i = 0; i < ransomNote.length(); i++)
{
if(mapping[ransomNote[i]] > 0) mapping[ransomNote[i]]--;
else return false;
}
return true;
}
};