
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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int CountCharacters(string[] words, string chars) {
6 int[] charCount = new int[26];
7 foreach (char c in chars) {
8 charCount[c - 'a']++;
9 }
10 int result = 0;
11 foreach (string word in words) {
12 int[] wordCount = new int[26];
13 foreach (char c in word) {
14 wordCount[c - 'a']++;
15 }
16 bool canForm = true;
17 for (int i = 0; i < 26; i++) {
18 if (wordCount[i] > charCount[i]) {
19 canForm = false;
20 break;
21 }
22 }
23 if (canForm) {
24 result += word.Length;
25 }
26 }
27 return result;
28 }
29 public static void Main(string[] args) {
30 Solution sol = new Solution();
31 string[] words = { "cat", "bt", "hat", "tree" };
32 string chars = "atach";
33 Console.WriteLine(sol.CountCharacters(words, chars)); // Output: 6
34 }
35}Similar to other implementations, this C# solution sets up arrays for character counts and iterates over the words to verify if they can be made from the available characters. A boolean flag helps to check if a word can be composed.
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.