[LeetCode] Find Words That Can Be Formed by Characters

1160. Find Words That Can Be Formed by Characters

You are given an array of strings words and a string chars.

A string is good if it can be formed by characters from chars (each character can only be used once).

Return the sum of lengths of all good strings in words.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
bool ok(vector<int>& A, vector<int>& B) {
for(int i = 0; i < 26; i++) {
if(A[i] < B[i]) return false;
}
return true;
}
public:
int countCharacters(vector<string>& words, string chars) {
vector<int> freq(26);
for(auto& ch : chars) freq[ch-'a'] += 1;
int res = 0;
for(auto& w : words) {
vector<int> now(26);
for(auto& ch : w) now[ch-'a'] += 1;
if(ok(freq,now)) res += w.size();
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/12/02/PS/LeetCode/find-words-that-can-be-formed-by-characters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.