题目:
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.
1 canConstruct("a", "b") -> false
2 canConstruct("aa", "ab") -> false
3 canConstruct("aa", "aab") -> true
代码:
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
if (ransomNote == "")
return true;
for (auto c : ransomNote){
int position = magazine.find_first_of(c);
if (position != magazine.npos)
magazine.erase(position, 1);
else
return false;
}
return true;
}
};
别人的:
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int mp[26] = {0};
for(auto c : magazine) {
mp[c - 'a']++;
}
for(auto r : ransomNote) {
mp[r - 'a']--;
if(mp[r - 'a'] < 0) return false;
}
return true;
}
};