[Solution]819. Most Common Word

·

1 min read

Problem

Problem_Link

Solutions (time, space)

O(n), O(n)

class Solution {
    public String mostCommonWord(String p, String[] banned) {
        Set<String> bannedWords = new HashSet<>(Arrays.asList(banned));
        Map<String, Integer> countedWords = new HashMap<>();


        String[] words = p.replaceAll("\\W+", " ").toLowerCase().split("\\s+");

        for (String word : words) {
            if (!bannedWords.contains(word)) {
                countedWords.put(word, countedWords.getOrDefault(word, 0) + 1);
            }
        }

        return Collections.max(countedWords.entrySet(),
                Map.Entry.comparingByValue()).getKey();
    }
}

Explanation

  • there is another way to solve: using Trie
  • Trie is specialized word search. but use more spaces
  • Trie used for search word recommendation, finding dictionary, or checking grammer