给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
如果可以,返回 true ;否则返回 false 。
magazine 中的每个字符只能在 ransomNote 中使用一次。
Plan1:暴力法
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
for(int i = 0; i < magazine.length(); i++){
for(int j = 0; j < ransomNote.length(); j++){
if(magazine[i] == ransomNote[j]){
ransomNote.erase(ransomNote.begin() + j);
break;
}
}
}
if(ransomNote.length() == 0){
return true;
}
return false;
}
};
Plan2:哈希解法
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int record[26] = {0};
for(int i = 0; i < magazine.size(); i++){
record[magazine[i] - 'a']++;
}
for(int j = 0; j < ransomNote.size(); j++){
record[ransomNote[j] - 'a']--;
}
for(int k = 0; k < 26; k++){
if(record[k] < 0) return false;
}
return true;
}
};