Skip to content

Commit cefc669

Browse files
solves most common word
1 parent d9e2d45 commit cefc669

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

Diff for: README.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# LeetCode Algorithms
22

3-
![problems-solved](https://img.shields.io/badge/Problems%20Solved-190/2081-1f425f.svg)
4-
![problems-solved-java](https://img.shields.io/badge/Java-190/2081-1abc9c.svg)
3+
![problems-solved](https://img.shields.io/badge/Problems%20Solved-191/2081-1f425f.svg)
4+
![problems-solved-java](https://img.shields.io/badge/Java-191/2081-1abc9c.svg)
55
![problems-solved-python](https://img.shields.io/badge/Python-186/2081-1abc9c.svg)
66
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md)
77
[![cp](https://img.shields.io/badge/also%20see-Competitve%20Programming-1f72ff.svg)](https://github.com/anishLearnsToCode/competitive-programming)
@@ -220,7 +220,7 @@
220220
| 806 | [Number of Lines to Write String](https://leetcode.com/problems/number-of-lines-to-write-string) | [![Java](assets/java.png)](src/NumberOfLinesToWriteInString.java) |
221221
| 811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count) | |
222222
| 812 | [Largest Triangle Area](https://leetcode.com/problems/largest-triangle-area) | [![Java](assets/java.png)](src/LargestTriangleArea.java) |
223-
| 819 | [Most Common Word](https://leetcode.com/problems/most-common-word) | |
223+
| 819 | [Most Common Word](https://leetcode.com/problems/most-common-word) | [![Java](assets/java.png)](src/MostCommonWord.java) |
224224
| 821 | [Shortest Distance to Character](https://leetcode.com/problems/shortest-distance-to-a-character) | |
225225
| 824 | [Goat Latin](https://leetcode.com/problems/goat-latin) | |
226226
| 830 | [Positions of Large Groups](https://leetcode.com/problems/positions-of-large-groups) | |

Diff for: src/MostCommonWord.java

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import java.util.Arrays;
2+
import java.util.Collections;
3+
import java.util.HashMap;
4+
import java.util.HashSet;
5+
import java.util.Map;
6+
import java.util.Set;
7+
8+
public class MostCommonWord {
9+
public String mostCommonWord(String paragraph, String[] banned) {
10+
String text = paragraph.replaceAll("[^a-zA-Z0-9 ]", " ").toLowerCase();
11+
Set<String> bannedWords = new HashSet<>(Arrays.asList(banned));
12+
Map<String, Integer> wordFrequencies = new HashMap<>();
13+
14+
for (String word : text.split("\\s+")) {
15+
if (!bannedWords.contains(word)) {
16+
wordFrequencies.put(word, wordFrequencies.getOrDefault(word, 0) + 1);
17+
}
18+
}
19+
20+
return Collections.max(wordFrequencies.entrySet(), Map.Entry.comparingByValue()).getKey();
21+
}
22+
}

0 commit comments

Comments
 (0)