Topic links:
Subject description:
Give you a "Glossary" (array of strings) words
and a "alphabet" (string) chars
.
If you can use chars
the "alphabet" (character) spelled out words
in a "word" (string), then we think you've mastered the word.
Note: Each time spelling chars
of each letter can only be used once.
Returns the vocabulary words
you master all the words and length.
Example:
Example 1:
输入:words = ["cat","bt","hat","tree"], chars = "atach" 输出:6 解释:可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。
Example 2:
输入:words = ["hello","world","leetcode"], chars = "welldonehoneyr" 输出:10 解释:可以形成字符串 "hello" 和 "world",所以答案是 5 + 5 = 10。
prompt:
1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
- All string contains only lowercase letters
Ideas:
- Statistics alphabet
chars
number of times each letter appears; - Check the glossary
words
each wordword
:- If the
word
number of times each letter appears all times equal to the corresponding letters appear in the vocabulary of less than 10,word
maychars
spell.
- If the
class Solution {
public int countCharacters(String[] words, String chars) {
int answer = 0;
// 统计“字母表”中每个字母出现的次数
int[] charsCount = count(chars);
for (String word : words) {
// 统计“词汇表”每个单词中每个字母出现的次数
int[] wordCount = count(word);
if (contains(charsCount, wordCount)) {
answer += word.length();
}
}
return answer;
}
// 统计字符串中每个字母出现的次数
private int[] count(String str) {
int[] counter = new int[26];
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
counter[c - 'a'] ++;
}
return counter;
}
// 检查字母表chars能否拼出单词word
private boolean contains(int[] charsCount, int[] wordCount) {
for (int i = 0; i < 26; i++) {
if (charsCount[i] < wordCount[i]) {
return false;
}
}
return true;
}
}