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