-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommonCharacters.java
More file actions
38 lines (30 loc) · 1.01 KB
/
Copy pathCommonCharacters.java
File metadata and controls
38 lines (30 loc) · 1.01 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
package LeetcodePractice;
import java.util.*;
public class CommonCharacters {
public static void main(String[] args) {
String[] words1 = {"bella","label","roller"};
System.out.println(commonChars(words1));
String[] words2 = {"cool","lock","cook"};
System.out.println(commonChars(words2));
}
public static List<String> commonChars(String[] words) {
int[] minFreq = new int[26];
Arrays.fill(minFreq, Integer.MAX_VALUE);
for (String word : words) {
int[] freq = new int[26];
for (char c : word.toCharArray()) {
freq[c - 'a']++;
}
for (int i = 0; i < 26; i++) {
minFreq[i] = Math.min(minFreq[i], freq[i]);
}
}
List<String> result = new ArrayList<>();
for (int i = 0; i < 26; i++) {
for (int j = 0; j < minFreq[i]; j++) {
result.add(String.valueOf((char)(i + 'a')));
}
}
return result;
}
}