[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 }

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/12813227.html