-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountCharacters.java
More file actions
40 lines (35 loc) · 1.13 KB
/
Copy pathCountCharacters.java
File metadata and controls
40 lines (35 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package LeetcodePractice;
import java.util.Arrays;
public class CountCharacters {
public int countCharacters(String[] words, String chars) {
int[] freq = new int[26];
for (char c : chars.toCharArray()) {
freq[c - 'a']++;
}
int total = 0;
for (String word : words) {
int[] temp = Arrays.copyOf(freq, 26);
boolean good = true;
for (char c : word.toCharArray()) {
if (temp[c - 'a'] == 0) {
good = false;
break;
}
temp[c - 'a']--;
}
if (good) {
total += word.length();
}
}
return total;
}
public static void main(String[] args) {
CountCharacters sol = new CountCharacters();
String[] words1 = {"cat","bt","hat","tree"};
String chars1 = "atach";
System.out.println(sol.countCharacters(words1, chars1));
String[] words2 = {"hello","world","leetcode"};
String chars2 = "welldonehoneyr";
System.out.println(sol.countCharacters(words2, chars2));
}
}