原题:
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
判断一个string里的所有字母是否全部来自另一个string(无视顺序),先把所有词库入map试水,结果:
Success
Runtime: 32 ms, faster than 45.58% of C++ online submissions for Ransom Note.
Memory Usage: 11 MB, less than 55.14% of C++ online submissions for Ransom Note.
代码:
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
map<char,int> lib;
for(int i=magazine.size()-1;i>=0;i--){
lib[magazine[i]]++;
}
for(int i=ransomNote.size()-1;i>=0;i--){
if(!lib[ransomNote[i]]){return false;}
else{lib[ransomNote[i]]--;}
}
return true;
}
};
修改一下代码把ransom入map就会快一点:
Success
Runtime: 24 ms, faster than 75.37% of C++ online submissions for Ransom Note.
Memory Usage: 11.1 MB, less than 45.81% of C++ online submissions for Ransom Note.
代码:
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
if(!ransomNote.size()){return true;}
map<char,int> lib;
for(int i=ransomNote.size()-1;i>=0;i--){
lib[ransomNote[i]]++;
}
map<char,int>::iterator it;
for(int i=magazine.size()-1;i>=0;i--){
it=lib.find(magazine[i]);
if(it==lib.end()){continue;}
if(lib[magazine[i]]>1){lib[magazine[i]]--;}
else if(lib[magazine[i]]==1){lib.erase(magazine[i]);}
if(!lib.size()){return true;}
}
return false;
}
};
还是不够快,想不如试一下数组哈希好了,结果反而变好了:
Success
Runtime: 16 ms, faster than 97.44% of C++ online submissions for Ransom Note.
Memory Usage: 10.7 MB, less than 87.57% of C++ online submissions for Ransom Note.
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int hash[26]={0};
for(int i=ransomNote.size()-1;i>=0;i--){
hash[ransomNote[i]-97]++;
}
for(int i=magazine.size()-1;i>=0;i--){
hash[magazine[i]-97]--;
}
for(int i=0;i<26;i++){
if(hash[i]>0){return false;}
}
return true;
}
};