topic
Give you a "Glossary" (array of strings) words and an "alphabet" (string) chars.
If you can spell out words in a "word" (string) with the chars in the "letter" (character), then we think you've mastered the word.
Note: Each time the spelling, chars each letter can only be used once.
Return vocabulary words in all the words you have mastered the sum of the lengths.
Example 1:
Input: words = [ "cat", "bt", "hat", "tree"], chars = "atach"
Output: 6
Explanation:
may form a string "cat" and "hat", so the answer is 3 + 3 = 6.
Example 2:
Input: words = [ "hello", "world", "leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation:
may form a string "hello" and "world", so the answer is 5 + 5 = 10.
Thinking
Thought the corresponding letter of the alphabet letters, and recording the corresponding frequency c hash table, a hash table is then additionally recording the corresponding letter words w of words, and frequency numbers, w in all the letters of the alphabet must be a subset of c, and when the frequency can not exceed, words are only words can be expressed in chars. Improvement: in the comments area to see an array of recording methods can be used, it will Biha Xi table faster, but the same ideas. To achieve the following:
class Solution {
public:
int countCharacters(vector<string>& words, string chars) {
if(words.empty()||chars.empty())
return 0;
unordered_map<char, int> c;
for(int i=0 ; i<chars.size(); i++){
char t=chars[i];
c.find(t)==c.end()?c[t]=1:c[t]++;
}
int ans=0;
for(int i=0; i<words.size(); i++){
unordered_map<char, int> w;
int j=0;
for(; j<words[i].size(); j++){
char t=words[i][j];
if(c.find(t)==c.end())
break;
w.find(t)==w.end()?w[t]=1:w[t]++;
if(w[t]>c[t])
break;
}
if(j==words[i].size())
ans+=words[i].size();
}
return ans;
}
};