-
Notifications
You must be signed in to change notification settings - Fork 0
/
1002.find-common-characters.java
47 lines (43 loc) · 1.24 KB
/
1002.find-common-characters.java
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
46
/*
* @lc app=leetcode id=1002 lang=java
*
* [1002] Find Common Characters
*/
// @lc code=start
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
public List<String> commonChars(String[] words) {
List<String> ret = new ArrayList<>();
if (words.length == 1) {
for (char ch : words[0].toCharArray()) ret.add(String.valueOf(ch));
return ret;
}
List<Map<Character, Integer>> maps = new ArrayList<>();
for (String word : words) {
maps.add(count(word));
}
for (char ch = 'a'; ch <= 'z'; ++ch) {
final char _ch = ch;
int times = (int) maps.stream()
.map(m -> m.getOrDefault(_ch, 0))
.mapToInt(x -> x)
.min().orElse(-1);
while (times != 0) {
ret.add(String.valueOf(ch));
times -= 1;
}
}
return ret;
}
private Map<Character, Integer> count(String s) {
Map<Character, Integer> ret = new HashMap<>();
for (char ch : s.toCharArray()) {
ret.put(ch, ret.getOrDefault(ch, 0) + 1);
}
return ret;
}
}
// @lc code=end