-
Notifications
You must be signed in to change notification settings - Fork 0
/
CommonCharacters.java
34 lines (28 loc) · 968 Bytes
/
CommonCharacters.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
class CommonCharacters {
public List<String> commonChars(String[] words) {
List<String> ans = new ArrayList<>();
String temp = words[0];
for (int i = 1; i < words.length; i++) {
temp = findCommonWords(temp, words[i]);
}
for (int i = 0; i < temp.length(); i++) {
ans.add(temp.charAt(i)+"");
}
return ans;
}
private static String findCommonWords(String first, String second) {
StringBuilder ans = new StringBuilder();
Map<Character, Integer> map = new HashMap<>();
for (Character c : first.toCharArray()) {
map.put(c, map.getOrDefault(c, 0)+1);
}
for (Character c : second.toCharArray()) {
if (map.containsKey(c)) {
ans.append(c);
if (map.get(c) > 1) map.put(c, map.get(c)-1);
else map.remove(c);
}
}
return ans.toString();
}
}