051104
题目
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
我的解题思路
这道题是查看字符串magazines是否包含了ransom note string,不管其出现的顺序只要每个字符及其次数能组会起来就行。因此,我们可以对magazines求一个map,存储其字符及其该字符出现的次数。之后再对ransom note string的字符进行判断,当ransom note string中出现该字符则减掉map中的数,若最后所有的字符对应的次数都大于等于0,则返回true,否则false。
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char, int> map(26);
for (int i = 0; i < magazine.size(); ++i)
++map[magazine[i]];
for (int j = 0; j < ransomNote.size(); ++j)
if (--map[ransomNote[j]] < 0)
return false;
return true;
}
};
去看了大佬的解答,不用map之类的stl库实现,而是只用了string的函数。tql~
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
for(char c: ransomNote){
int found = magazine.find(c);
if(found == string::npos){
return false;
}
magazine[found] = ' ';
}
return true;
}
};