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; } };
|