First: Problem’s Description
Second: Problem’s Solution
Evidently we can use a hash vector to save the frequency of the letters in chars
. then we traverse the vector words
and each time we traverse a string in words
, we copy Hash
as tmpHash
to avoid change the raw Hash
Third: Code For Solution
class Solution {
public:
int countCharacters(vector<string>& words, string chars) {
vector<int> Hash(26, 0);
for(int i = 0; i < chars.size(); i++)
Hash[chars[i] - 'a']++;
int len = 0;
for(int i = 0; i < words.size(); i++){
auto tmpHash = Hash;
int tmplen = words[i].size();
for(int j = 0; j < words[i].size(); j++){
if(tmpHash[words[i][j] - 'a']-- > 0){}
else{
tmplen = 0;
break;
}
}
len += tmplen;
}
return len;
}
};