Input: words =["cat","bt","hat","tree"], chars ="atach" Output:6 Explanation: The strings that can be formed are "cat" and "hat" so the answer is3+3=6.
Input: words =["hello","world","leetcode"], chars ="welldonehoneyr" Output:10 Explanation: The strings that can be formed are "hello" and "world" so the answer is5+5=10.
We count the frequency of each character in chars and for each word, check if it can be formed using the available characters (each used at most once).
classSolution {
public:int countCharacters(vector<string>& words, string chars) {
vector<int> cnt(26, 0);
for (char c : chars) cnt[c -'a']++;
int ans =0;
for (auto& w : words) {
vector<int> wc(26, 0);
for (char c : w) wc[c -'a']++;
bool good = true;
for (int i =0; i <26; ++i) {
if (wc[i] > cnt[i]) { good = false; break; }
}
if (good) ans += w.size();
}
return ans;
}
};
classSolution {
publicintcountCharacters(String[] words, String chars) {
int[] cnt =newint[26];
for (char c : chars.toCharArray()) cnt[c -'a']++;
int ans = 0;
for (String w : words) {
int[] wc =newint[26];
for (char c : w.toCharArray()) wc[c -'a']++;
boolean good =true;
for (int i = 0; i < 26; i++) {
if (wc[i]> cnt[i]) { good =false; break; }
}
if (good) ans += w.length();
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funcountCharacters(words: Array<String>, chars: String): Int {
val cnt = IntArray(26)
for (c in chars) cnt[c - 'a']++var ans = 0for (w in words) {
val wc = IntArray(26)
for (c in w) wc[c - 'a']++var good = truefor (i in0 until 26) {
if (wc[i] > cnt[i]) { good = false; break }
}
if (good) ans += w.length
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defcountCharacters(self, words: list[str], chars: str) -> int:
from collections import Counter
cnt = Counter(chars)
ans =0for w in words:
wc = Counter(w)
if all(wc[c] <= cnt[c] for c in wc):
ans += len(w)
return ans
impl Solution {
pubfncount_characters(words: Vec<String>, chars: String) -> i32 {
letmut cnt = [0; 26];
for c in chars.chars() {
cnt[c asusize-'a'asusize] +=1;
}
letmut ans =0;
for w in words {
letmut wc = [0; 26];
for c in w.chars() {
wc[c asusize-'a'asusize] +=1;
}
letmut good =true;
for i in0..26 {
if wc[i] > cnt[i] { good =false; break; }
}
if good { ans += w.len() asi32; }
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
countCharacters(words: string[], chars: string):number {
constcnt= Array(26).fill(0);
for (constcofchars) cnt[c.charCodeAt(0) -97]++;
letans=0;
for (constwofwords) {
constwc= Array(26).fill(0);
for (constcofw) wc[c.charCodeAt(0) -97]++;
letgood=true;
for (leti=0; i<26; i++) {
if (wc[i] >cnt[i]) { good=false; break; }
}
if (good) ans+=w.length;
}
returnans;
}
}