383. 赎金信
https://leetcode-cn.com/problems/ransom-note/
难度简单
给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
如果可以,返回 true ;否则返回 false 。
magazine 中的每个字符只能在 ransomNote 中使用一次。
解法一 暴力破解法
双层for循环暴力破解
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;
}else{
return false;
}
}
};
解法二 哈希法
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int com[26]={0};
for(int i = 0 ;i<magazine.length();i++){
com[magazine[i]-'a']++;
}
for(int j = 0 ;j<ransomNote.length();j++){
if(com[ransomNote[j]-'a']==0){
return false;
}
else{
com[ransomNote[j]-'a']--;
}
}
return true;
}
};









