Skip to content

Commit 412ec9d

Browse files
solves find common characters
1 parent 742c396 commit 412ec9d

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@
269269
| 993 | [Cousins in Binary Tree](https://leetcode.com/problems/cousins-in-binary-tree) | [![Java](assets/java.png)](src/CousinsInBinaryTree.java) |
270270
| 997 | [Find the Town Judge](https://leetcode.com/problems/find-the-town-judge) | [![Java](assets/java.png)](src/FindTheTownJudge.java) |
271271
| 999 | [Available Captures for Rook](https://leetcode.com/problems/available-captures-for-rook) | [![Java](assets/java.png)](src/AvailableCapturesForRook.java) |
272-
| 1002 | [Find Common Characters](https://leetcode.com/problems/find-common-characters) | |
272+
| 1002 | [Find Common Characters](https://leetcode.com/problems/find-common-characters) | [![Java](assets/java.png)](src/FindCommonCharacters.java) |
273273
| 1005 | [Maximize Sum of Array After K Negations](https://leetcode.com/problems/maximize-sum-of-array-after-k-negations) | |
274274
| 1009 | [Complement of Base 10 Integer](https://leetcode.com/problems/complement-of-base-10-integer) | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/NumberComplement.java) |
275275
| 1010 | [Pairs of Songs With Total Durations Divisible by 60](https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60) | |

src/FindCommonCharacters.java

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import java.util.ArrayList;
2+
import java.util.HashMap;
3+
import java.util.List;
4+
import java.util.Map;
5+
6+
public class FindCommonCharacters {
7+
public List<String> commonChars(String[] words) {
8+
Map<Character, Integer> commonChars = getCharsFrequency(words[0]);
9+
Map<Character, Integer> wordChars;
10+
for (int i = 1 ; i < words.length ; i++) {
11+
wordChars = getCharsFrequency(words[i]);
12+
for (char letter : commonChars.keySet()) {
13+
commonChars.put(letter, Math.min(commonChars.get(letter), wordChars.getOrDefault(letter, 0)));
14+
}
15+
}
16+
return toList(commonChars);
17+
}
18+
19+
private List<String> toList(Map<Character, Integer> characters) {
20+
List<String> result = new ArrayList<>();
21+
for (Map.Entry<Character, Integer> entry : characters.entrySet()) {
22+
if (entry.getValue() > 0) {
23+
for (int i = 0 ; i < entry.getValue() ; i++) result.add(entry.getKey() + "");
24+
}
25+
}
26+
return result;
27+
}
28+
29+
private Map<Character, Integer> getCharsFrequency(String string) {
30+
Map<Character, Integer> result = new HashMap<>();
31+
char character;
32+
for (int index = 0 ; index < string.length() ; index++) {
33+
character = string.charAt(index);
34+
result.put(character, result.getOrDefault(character, 0) + 1);
35+
}
36+
return result;
37+
}
38+
}

0 commit comments

Comments
 (0)