
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.
1import java.util.*;
2
3public class Solution {
4 public int countCharacters(String[] words, String chars) {
5 int[] charCount = new int[26];
6 for (char ch : chars.toCharArray()) {
7 charCount[ch - 'a']++;
8 }
9 int result = 0;
10 for (String word : words) {
11 int[] wordCount = new int[26];
12 for (char ch : word.toCharArray()) {
13 wordCount[ch - 'a']++;
14 }
15 if (canFormWord(wordCount, charCount)) {
16 result += word.length();
17 }
18 }
19 return result;
20 }
21 private boolean canFormWord(int[] wordCount, int[] charCount) {
22 for (int i = 0; i < 26; i++) {
23 if (wordCount[i] > charCount[i]) {
24 return false;
25 }
26 }
27 return true;
28 }
29 public static void main(String[] args) {
30 Solution s = new Solution();
31 String[] words = {"cat", "bt", "hat", "tree"};
32 String chars = "atach";
33 System.out.println(s.countCharacters(words, chars)); // Output: 6
34 }
35}The Java solution encapsulates the logic in a class with methods for counting characters and checking if a word can be formed. It uses arrays for character counting and checks word formations using a helper method.
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.