https://leetcode.com/problems/ransom-note/description/
Solution 1. construct a map: char -> nums of appearance
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char, int> m(26);
for(int i = 0; i < magazine.size(); i++) {
++m[magazine[i]];
}
for(int i = 0; i < ransomNote.size(); i++) {
--m[ransomNote[i]];
if(m[ransomNote[i]]<0) return false;
}
return true;
}
Solution 2. use a vector for the map (fastest)
bool canConstruct(string ransomNote, string magazine) {
vector<int> m(26+'a',0);
for(char c: magazine) {
++m[c];
}
for(char c: ransomNote) {
if(--m[c]<0) return false;
}
return true;
}
Solution 3. sort and compare (much slower).
bool canConstruct(string ransomNote, string magazine) {
int i, j;
sort(ransomNote.begin(),ransomNote.end());
sort(magazine.begin(),magazine.end());
if(ransomNote.size()>magazine.size()) return false;
for( i=0,j=0;i<ransomNote.size()&&j<magazine.size();) {
if(ransomNote[i] == magazine[j]) {
i++;
j++;
}
else if(ransomNote[i]<magazine[j]) return false;
else j++;
}
return i==ransomNote.size();
}
No comments:
Post a Comment