0%

LeetCode-1002

题目

结果

代码

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
41
42
43
44
45
class Solution {
public List<String> commonChars(String[] A) {
Map<Character, Integer> map = new HashMap<>();
List<String> ans = new LinkedList<>();

String str = A[0];
for (char ch : str.toCharArray()) {
if (bothHave(A, ch)) {
map.put(ch, 1);
}
}

for (char key : map.keySet()) {
map.put(key, minTime(key, A));
for (int i = 0; i < map.get(key); i++) {
ans.add("" + key);
}
}

return ans;
}

private boolean bothHave(String[] strings, char ch) {
for (String str : strings) {
if (!str.contains("" + ch)) {
return false;
}
}
return true;
}

private int minTime(char key, String[] strings) {
int ans = Integer.MAX_VALUE;
for (String s : strings) {
int time = 0;
for (char ch : s.toCharArray()) {
if (ch == key) {
time++;
}
}
ans = Math.min(ans, time);
}
return ans;
}
}