给定一个段落和一组限定词,返回最频繁的非限定单词。已知至少有一个单词是非限定的,并且答案唯一。
限定词都是以小写字母给出,段落中的单词大小写不敏感。结果请返回小写字母。
样例
输入:
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
输出:"ball"
解释:
"hit" 出现3次但是限定词。
"ball" 出现两次,是最频繁的非限定词。
注意段落中大小写不敏感。
标点符号请忽略 (即使紧挨单词,例如"ball,"),
注意事项
- 1 <= paragraph.length <= 1000.
- 1 <= banned.length <= 100.
- 1 <= banned[i].length <= 10.
- 答案唯一,并且返回小写(即使以大写字母出现在段落中就,或是一个专有名词.)
- 段落仅由字母、空格、标点
!?',;.组成。 - 不同的单词会被空格隔开.
- 没有连字符或者连字单词.
- 单词仅由小写字母组成,没有所有格或别的标点符号。
解题思路:
典型的HashMap题目,注意如果有多个标志分割,可以使用正则表达式。
public class Solution {
/**
* @param paragraph:
* @param banned:
* @return: nothing
*/
public String mostCommonWord(String paragraph, String[] banned) {
Map<String,Integer> map = new HashMap<>();
Set<String> set = new HashSet<>();
for(String s : banned)
set.add(s);
String[] words = paragraph.toLowerCase().split("[!?',;. ]");
String res = null;
int maxTimes = 0;
for(String s : words){
if(s.length()==0 || set.contains(s))
continue;
if(map.get(s) == null)
map.put(s,1);
else
map.put(s,map.get(s) + 1);
if(map.get(s) > maxTimes){
res = s;
maxTimes = map.get(s);
}
}
return res;
}
}

本文介绍了一种基于HashMap的数据结构解决算法问题的方法,通过实例演示如何找出一段文本中出现频率最高的非限定词,同时考虑了大小写不敏感和忽略标点符号的要求。
210

被折叠的 条评论
为什么被折叠?



