JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.

The words in paragraph are case-insensitive and the answer should be returned in lowercase.

Example 1:

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.

Example 2:

Input: paragraph = "a.", banned = []
Output: "a"

Code

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

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

        String ans = "";
        int maxCount = 0;
        Map<String, Integer> wordCount = new HashMap();

        StringBuilder sb = new StringBuilder();

        char[] chars = paragraph.toCharArray();

        for (int i = 0; i < chars.length; ++i) {
            char currChar = chars[i];
            // 使用isLetter判断
            if (Character.isLetter(currChar)) {
                sb.append(Character.toLowerCase(currChar));
                if (i != chars.length - 1) {
                    continue;
                }
            }

            if (sb.length() > 0) {
                String word = sb.toString();

                if (!bannedWords.contains(word)) {
                    int newCount = wordCount.getOrDefault(word, 0) + 1;
                    wordCount.put(word, newCount);
                    if (newCount > maxCount) {
                        ans = word;
                        maxCount = newCount;
                    }
                }

                sb = new StringBuilder();
            }
        }

        return ans;
    }
}