
Sponsored
Sponsored
This approach involves counting the frequency of each character in the 'chars' string. For each word, check if the word can be constructed using these characters, respecting their frequencies.
Time Complexity: O(N*K + C), where N = number of words, K = average length of the word, C = length of 'chars'.
Space Complexity: O(1), as the auxiliary space used is constant, i.e., the two arrays of size 26.
1#include <iostream>
2#include <vector>
3#include <string>
4using namespace std;
5
6int countCharacters(vector<string>& words, string chars) {
7 vector<int> charCount(26, 0);
8 for (char c : chars) {
9 charCount[c - 'a']++;
10 }
11 int result = 0;
12 for (string word : words) {
13 vector<int> wordCount(26, 0);
14 for (char c : word) {
15 wordCount[c - 'a']++;
16 }
17 bool canForm = true;
18 for (int i = 0; i < 26; i++) {
19 if (wordCount[i] > charCount[i]) {
20 canForm = false;
21 break;
22 }
23 }
24 if (canForm) {
25 result += word.length();
26 }
27 }
28 return result;
29}
30
31int main() {
32 vector<string> words = {"cat", "bt", "hat", "tree"};
33 string chars = "atach";
34 cout << countCharacters(words, chars) << endl; // Output: 6
35 return 0;
36}The C++ solution is similar to the C solution. It uses vectors to keep track of the character counts both for 'chars' and each word. The logic checks if the word can be formed from 'chars' by comparing character requirements.
This approach utilizes hash maps to count the frequency of characters in both the 'chars' string and each word. The map allows for dynamic sizing and flexibility with character counts.
Time Complexity: O(N*K + C), where N = number of words, K = average length of the word, C = length of 'chars'.
Space Complexity: O(1), additional space overhead is minimal with the unordered maps.
1#include <iostream>
2#include <vector>
3#include <string>
4#include <unordered_map>
5using namespace std;
int countCharacters(vector<string>& words, string chars) {
unordered_map<char, int> charMap;
for (char c : chars) {
charMap[c]++;
}
int result = 0;
for (string word : words) {
unordered_map<char, int> wordMap;
for (char c : word) {
wordMap[c]++;
}
bool canForm = true;
for (auto& entry : wordMap) {
if (entry.second > charMap[entry.first]) {
canForm = false;
break;
}
}
if (canForm) {
result += word.length();
}
}
return result;
}
int main() {
vector<string> words = {"cat", "bt", "hat", "tree"};
string chars = "atach";
cout << countCharacters(words, chars) << endl; // Output: 6
return 0;
}This solution counts the frequencies of characters using hash maps for both 'chars' and each word. It checks if the words can be formed by comparing counts in these maps and adds the lengths of words that can be formed.