给定一个段落和一组限定词,返回最频繁的非限定单词。已知至少有一个单词是非限定的,并且答案唯一。
限定词都是以小写字母给出,段落中的单词大小写不敏感。结果请返回小写字母。
样例1
输入: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." 和 banned = ["hit"]
输出: "ball"
解释:
"hit" 出现3次但是限定词。
"ball" 出现两次,是最频繁的非限定词。
注意段落中大小写不敏感。
标点符号请忽略 (即使紧挨单词,例如"ball,"),
样例2
输入: paragraph = "a a a b b c c d" 和 banned = ["a","b"]
输出: "c"
解释:
"a"和"b"都是限定词
"c"出现了2次,而"d"只出现过一次
所以输出"c"
注意事项
1 <= paragraph.length <= 1000.
1 <= banned.length <= 100.
1 <= banned[i].length <= 10.
答案唯一,并且返回小写(即使以大写字母出现在段落中就,或是一个专有名词.)
段落仅由字母、空格、标点!?',;.组成。
不同的单词会被空格隔开.
没有连字符或者连字单词.
单词仅由小写字母组成,没有所有格或别的标点符号。
class Solution {
public:
/**
* @param paragraph:
* @param banned:
* @return: nothing
*/
string mostCommonWord(string ¶graph, vector<string> &banned) {
//
map<string,int> ans;
set<string> judge(banned.begin(),banned.end());//找限定词
string temp="";//得到每个单词
for (int i = 0; i < paragraph.size(); i++) {//往map中添加单词
/* code */
if(isalpha(paragraph[i]))
{
if(isupper(paragraph[i])) temp+=tolower(paragraph[i]);
else temp+=paragraph[i];
}
else if(paragraph[i]==' '){ans[temp]++;temp="";}
}
ans[temp]++;//最后一个字符必为字母,单独处理
int Max=0;
for (auto i : ans) {
/* code */
if(!judge.count(i.first)&&i.second>Max)//不是限定词且出现次数最大
{
temp=i.first;//目前结果
Max=i.second;//目前最大出现次数
}
}
return temp;
}
};