题目描述
思路分析
我们既统计“字母表”中字母出现的次数,也统计单词中字母出现的次数。如果单词中每种字母出现的次数都小于等于字母表中字母出现的次数,那么这个单词就可以由字母表拼出来。
代码实现
package LeetCode;
public class CountCharacters {
public static void main(String[] args) {
}
public int countCharacters(String[] words, String chars) {
int[] chars_count = count(chars);// 统计字母表的字母出现次数
int res = 0;
for (String word : words) {
int[] word_count = count(word);// 统计单词的字母出现次数
if (contains(chars_count, word_count)) {
res += word.length();
}
}
return res;
}
// 检查字母表的字母出现次数是否覆盖单词的字母出现次数
private boolean contains(int[] chars_count, int[] word_count) {
for (int i = 0; i < 26; i++) {
if (chars_count[i] < word_count[i]) {
return false;
}
}
return true;
}
// 统计 26 个字母出现的次数
private int[] count(String word) {
int[] counter = new int[26];
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
counter[c - 'a']++;
}
return counter;
}
}