[LeetCode] 819. Most Common Word

Posted aaronliu1991

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 819. Most Common Word相关的知识,希望对你有一定的参考价值。

最常见的单词。题意是给一个paragraph字符串和一个String[],包含了一些被禁的单词。请你返回paragraph中出现次数最多的没有被禁的单词。例子,

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.

思路很直接,先用hashset记录所有被ban的单词,然后遍历paragraph,计算其他单词的出现次数,最后返回出现次数最多的那个单词。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public String mostCommonWord(String paragraph, String[] banned) {
 3         String[] words = paragraph.toLowerCase().split("\W+");
 4 
 5         // add banned words to set
 6         HashSet<String> set = new HashSet<>();
 7         for (String word : banned) {
 8             set.add(word);
 9         }
10 
11         // add paragraph words to hashmap
12         HashMap<String, Integer> map = new HashMap<>();
13         for (String word : words) {
14             if (!set.contains(word)) {
15                 map.put(word, map.getOrDefault(word, 0) + 1);
16             }
17         }
18 
19         // get the most freq word
20         int max = 0;
21         String res = "";
22         for (String str : map.keySet()) {
23             if (map.get(str) > max) {
24                 max = map.get(str);
25                 res = str;
26             }
27         }
28         return res;
29     }
30 }

 

以上是关于[LeetCode] 819. Most Common Word的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 819. Most Common Word

leetcode Most Common Word——就是在考察自己实现split

819. Most Common Word - Easy

819. Most Common Word

819. Most Common Word 统计高频词(暂未被禁止)

leetcode819