Find Words That Can Be Formed by Characters LeetCode solution in C++

1
class Solution {
2
public:
3
int countCharacters(vector<string> &words, string chars) {
4
vector<int> dp(26, 0);
5
vector<int> dp2(26, 0);
6
for (int i = 0; i < chars.size(); i++) {
7
dp[chars[i] - 'a']++;
8
}
9
dp2 = dp;
10
bool flg = false;
11
int cnt = 0;
12
for (int i = 0; i < words.size(); i++) {
13
string a = words[i];
14
for (int j = 0; j < a.size(); j++) {
15
if (dp[a[j] - 'a'] > 0) {
16
dp[a[j] - 'a']--;
17
} else {
18
flg = true;
19
dp = dp2;
20
break;
21
}
22
}
23
if (!flg) {
24
cnt += a.size();
25
}
26
dp = dp2;
27
flg = false;
28
}
29
return cnt;
30
}
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0