题目来源
题目详情
题目解答
显然,对于一个单词 word,只要其中的每个字母的数量都不大于 chars 中对应的字母的数量,那么就可以用 chars 中的字母拼写出 word
class Solution {
public:
int countCharacters(vector<string>& words, string chars) {
vector<int> freq_bucket(26, 0);
for(char ch : chars){
freq_bucket[ch - 'a']++;
}
int sum = 0;
for(const string& word : words){
bool ok = true;
vector<int> freq(freq_bucket);
for(char ch : word){
freq[ch - 'a']--;
if(freq[ch - 'a'] < 0){
ok = false;
break;
}
}
if(ok){
sum = sum + word.length();
}
}
return sum;
}
};
// 所有字符串中都仅包含小写英文字母
public static int countCharacters(String[] words, String chars) {
int count = 0;
int[] Hasi = new int[26];
for (int i = 0; i < chars.length(); i++) {
Hasi[chars.charAt(i) - 'a'] ++;
}
for (String word: words ) {
int[] cc = Arrays.copyOf(Hasi, Hasi.length);
boolean flag = true;
for (char c: word.toCharArray()){
if (cc[c-'a'] == 0){
flag = false;
break;
}
cc[c-'a']--;
}
if (flag){
count = count + word.length();
}
}
return count;
}
public static void main(String[] args) {
System.out.println(countCharacters(new String[]{"cat","bt","hat","tree"}, "atach"));
}