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
解题思路:字符串匹配,勒索字符串是否能由杂志字符串构成。将二十六个字母在magazine字符串出现的次数存储在数组中,将数组对应字母减去ransom字符串的每个字符出现的次数
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
vector<char>ran;
int a[26]={0};
for(auto x:ransomNote){
ran.push_back(x);
}
for(auto x:magazine){
a[x-'a']++;
}
for(int i=0;i<ran.size();i++){
if(--a[ran[i]-'a']<0){
return false;
}
}
return true;
}
};