Most Common Word
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"
Constraints:
1 <= paragraph.length <= 1000
paragraph consists of English letters, space ' ', or one of the symbols: "!?',;.".
0 <= banned.length <= 100
1 <= banned[i].length <= 10
banned[i] consists of only lowercase English letters.
思路一:分割字符串,然后统计。由于用了正则,效率会差很多,自己实现分割算法效率会好很多。
public static String mostCommonWord(String paragraph, String[] banned) {
Map<String, Integer> map = new HashMap<>();
String[] arr = paragraph.split("[!?',;.\\s]");
for (String s : arr) {
if (s.isEmpty()) continue;
map.compute(s.toLowerCase(), (k, v) -> v == null ? 1 : v + 1);
}
for (String s : banned) {
map.remove(s);
}
int max = 0;
String val = "";
for (Map.Entry<String, Integer> e : map.entrySet()) {
if (e.getValue() > max) {
max = e.getValue();
val = e.getKey();
}
}
return val;
}
标签:hit,String,banned,819,paragraph,easy,word,words,leetcode
From: https://www.cnblogs.com/iyiluo/p/16870946.html