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.
Note:
1 <= paragraph.length <= 1000
.0 <= banned.length <= 100
.1 <= banned[i].length <= 10
.- The answer is unique, and written in lowercase (even if its occurrences in
paragraph
may have uppercase symbols, and even if it is a proper noun.) paragraph
only consists of letters, spaces, or the punctuation symbols!?',;.
- There are no hyphens or hyphenated words.
- Words only consist of letters, never apostrophes or other punctuation symbols.
最常见的单词。题意是给一个paragraph字符串和一个String[],包含了一些被禁的单词。请你返回paragraph中出现次数最多的没有被禁的单词。
思路很直接,先用hashset记录所有被ban的单词,然后遍历paragraph,计算其他单词的出现次数,最后返回出现次数最多的那个单词。Java实现的具体细节,有如下几个步骤
- 将string变成string array
- 把所有内容convert成小写字母
- 在convert成string array的同时,用正则表达式跳过所有non word character。\W+的意思是跳过多个所有non word character,如果只跳过一个的话就不用放+
时间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 }