Skip to content

Commit 2692273

Browse files
committed
Modified one solution
1 parent ee9d31e commit 2692273

File tree

1 file changed

+25
-29
lines changed

1 file changed

+25
-29
lines changed
Lines changed: 25 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,29 @@
11
class Solution {
2-
public int countCharacters(String[] words, String chars) {
3-
int goodWordsLength = 0;
4-
Map<Character, Integer> charsMap = getMap(chars);
5-
6-
for (String word : words) {
7-
Map<Character, Integer> wordMap = getMap(word);
8-
boolean allFound = true;
9-
for (Character character : wordMap.keySet()) {
10-
if (charsMap.getOrDefault(character, 0) < wordMap.get(character)) {
11-
allFound = false;
12-
break;
13-
}
14-
}
15-
16-
if (allFound) {
17-
goodWordsLength +=word.length();
18-
}
19-
}
20-
21-
22-
return goodWordsLength;
2+
public int countCharacters(String[] words, String chars) {
3+
Map<Character, Integer> charFreq = getMap(chars);
4+
int length = 0;
5+
for (String word : words) {
6+
if (canBeFormed(charFreq, getMap(word))) {
7+
length += word.length();
8+
}
239
}
24-
25-
private Map<Character, Integer> getMap(String s) {
26-
Map<Character, Integer> map = new HashMap<>();
27-
for (char c : s.toCharArray()) {
28-
map.put(c, map.getOrDefault(c, 0) + 1);
29-
}
30-
31-
return map;
10+
return length;
11+
}
12+
13+
private Map<Character, Integer> getMap(String s) {
14+
Map<Character, Integer> map = new HashMap<>();
15+
for (char c : s.toCharArray()) {
16+
map.put(c, map.getOrDefault(c, 0) + 1);
3217
}
18+
return map;
19+
}
20+
21+
private boolean canBeFormed(Map<Character, Integer> main, Map<Character, Integer> toBeChecked) {
22+
for (Character key : toBeChecked.keySet()) {
23+
if (main.getOrDefault(key, 0) < toBeChecked.get(key)) {
24+
return false;
25+
}
26+
}
27+
return true;
28+
}
3329
}

0 commit comments

Comments
 (0)