Skip to content

Commit 22b12be

Browse files
authored
Update Find Common Characters.java
1 parent 1953be1 commit 22b12be

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

Easy/Find Common Characters.java

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,23 @@
11
class Solution {
2-
public List<String> commonChars(String[] A) {
3-
int[][] counter = new int[A.length][26];
4-
for (int i = 0; i < A.length; i++) {
5-
for (char c : A[i].toCharArray()) {
6-
counter[i][c - 'a']++;
2+
public List<String> commonChars(String[] words) {
3+
int[] commonFrequency = new int[26];
4+
Arrays.fill(commonFrequency, Integer.MAX_VALUE);
5+
for (String word : words) {
6+
int[] wordFreq = new int[26];
7+
for (char c : word.toCharArray()) {
8+
wordFreq[c - 'a']++;
9+
}
10+
for (int i = 0; i < 26; i++) {
11+
commonFrequency[i] = Math.min(commonFrequency[i], wordFreq[i]);
712
}
813
}
9-
List<String> list = new ArrayList<>();
14+
List<String> result = new ArrayList<>();
1015
for (int i = 0; i < 26; i++) {
11-
int minCount = Integer.MAX_VALUE;
12-
for (int j = 0; j < counter.length; j++) {
13-
minCount = Math.min(minCount, counter[j][i]);
14-
}
15-
while (minCount-- > 0) {
16-
list.add(String.valueOf((char) (97 + i)));
16+
int count = commonFrequency[i];
17+
while (count-- > 0) {
18+
result.add(String.valueOf((char) (97 + i)));
1719
}
1820
}
19-
return list;
21+
return result;
2022
}
2123
}

0 commit comments

Comments
 (0)