Skip to content

Latest commit

 

History

History
29 lines (23 loc) · 996 Bytes

Leetcode_819_MostCommonWord.md

File metadata and controls

29 lines (23 loc) · 996 Bytes

Leetcode 819: Most Common Word

Solution

class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
        Map<String, Integer> wordCountMap = new HashMap<>();
        Set<String> bannedSet = new HashSet<>(List.of(banned));
        List<String> words = Arrays.stream(paragraph.replaceAll("[!?',;.]", " ").toLowerCase().split(" "))
                .filter(word -> !bannedSet.contains(word) && !word.isEmpty()).collect(Collectors.toList());

        String mostFrequentWord = "";
        int mostFrequentWordCount = 0;
        for (String word : words) {
            wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);

            if (wordCountMap.get(word) > mostFrequentWordCount) {
                mostFrequentWord = word;
                mostFrequentWordCount = wordCountMap.get(word);
            }
        }

        return mostFrequentWord;
    }
}