码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 819. Most Common Word

时间:2020-05-01 14:44:28      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:pre   set   out   ignore   没有   string   lock   hat   def   

最常见的单词。题意是给一个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

标签:pre   set   out   ignore   没有   string   lock   hat   def   

原文地址:https://www.cnblogs.com/aaronliu1991/p/12813227.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!