819.Most-Common-Word

819. Most Common Word

题目地址

https://leetcode.com/problems/most-common-word/

题目描述

Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words.  It is guaranteed there is at least one word that isn't banned, and that the answer is unique.

Words in the list of banned words are given in lowercase, and free of punctuation.  Words in the paragraph are not case sensitive.  The answer is in lowercase.

Example:

Input: 
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
Output: "ball"
Explanation: 
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. 

Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"), 
and that "hit" isn't the answer even though it occurs more because it is banned.

代码

Approach #1 Counting

Complexity Analysis:

  • Time Complexity: O(P + B), where P is the size of paragraph and B is the size of banned.

  • Space Complexity: O(_P+_B), to store the count and the banned set.

class Solution {
        public String mostCommonWord(String paragraph, String[] banned) {
      if (paragraph == null || paragraph.length() == 0) return null;

      Set<String> banset = new HashSet();
      if (banned != null) {
          for (String word : banned) {
              banset.add(word);
          }
      }

      Map<String, Integer> count = new HashMap();

      String ans = "";
      int ansfreq = 0;

      StringBuilder word = new StringBuilder();
      paragraph += ".";
      for (char c : paragraph.toCharArray()) {
          if (Character.isLetter(c)) {
              if (isSymbol(c)) {
                  continue;
              } else {
                  word.append(Character.toLowerCase(c));
              }
          } else if (word.length() > 0) {
              String finalword = word.toString();
              if (!banset.contains(finalword)) {
                  count.put(finalword, count.getOrDefault(finalword, 0) + 1);
                  if (count.get(finalword) > ansfreq) {
                      ans = finalword;
                      ansfreq = count.get(finalword);
                  }
              }

              word = new StringBuilder();
          }
      }

      return ans;
      }

       private boolean isSymbol(char c) {
      return c == ' ' ||
          c == '!' ||
          c == '?' ||
          c == '\\' ||
          c == ',' ||
          c == ';' ||
          c == '.' ;
  }
}

Approach #2

class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {

        // 1). replace the punctuations with spaces,
        // and put all letters in lower case
        String normalizedStr = paragraph.replaceAll("[^a-zA-Z0-9 ]", " ").toLowerCase();

        // 2). split the string into words
        String[] words = normalizedStr.split("\\s+");

        Set<String> bannedWords = new HashSet();
        for (String word : banned)
            bannedWords.add(word);

        Map<String, Integer> wordCount = new HashMap();
        // 3). count the appearance of each word, excluding the banned words
        for (String word : words) {
            if (!bannedWords.contains(word))
                wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
        }

        // 4). return the word with the highest frequency
        return Collections.max(wordCount.entrySet(), Map.Entry.comparingByValue()).getKey();
    }
}

Last updated