LeetCode 819: Most Common Word
Problem Description
Explanation
To solve this problem, we can follow these steps:
- Preprocess the paragraph to extract words and convert them to lowercase.
- Create a set of banned words for efficient lookup.
- Count the frequency of each non-banned word using a hashmap.
- Find the word with the highest frequency that is not banned.
Time complexity: O(n) where n is the length of the paragraph Space complexity: O(n) for storing the word frequencies
Solutions
import java.util.*;
class Solution {
public String mostCommonWord(String paragraph, String[] banned) {
Set<String> bannedSet = new HashSet<>(Arrays.asList(banned));
Map<String, Integer> wordCount = new HashMap<>();
String[] words = paragraph.toLowerCase().split("[^a-zA-Z]+");
for (String word : words) {
if (!bannedSet.contains(word)) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
}
int maxCount = 0;
String mostCommonWord = "";
for (String word : wordCount.keySet()) {
if (wordCount.get(word) > maxCount) {
maxCount = wordCount.get(word);
mostCommonWord = word;
}
}
return mostCommonWord;
}
}
Related LeetCode Problems
Loading editor...