# 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: &#x4F;*(\_P*+\_B), to store the `count` and the banned set.

```java
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

```java
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();
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/string/819.most-common-word.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
