题目:
给定一个段落 (paragraph) 和一个禁用单词列表 (banned)。返回出现次数最多,同时不在禁用列表中的单词。
题目保证至少有一个词不在禁用列表中,而且答案唯一。
禁用列表中的单词用小写字母表示,不含标点符号。段落中的单词不区分大小写。答案都是小写字母
例子:
输入:
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
输出: "ball"
解释:
"hit" 出现了3次,但它是一个禁用的单词。
"ball" 出现了2次 (同时没有其他单词出现2次),所以它是段落里出现次数最多的,且不在禁用列表中的单词。
注意,所有这些单词在段落里不区分大小写,标点符号需要忽略(即使是紧挨着单词也忽略, 比如 "ball,"),
"hit"不是最终的答案,虽然它出现次数更多,但它在禁用单词列表中。
结果:
#include<iostream>
#include<iostream>
#include<unordered_map>
#include<unordered_set>
#include<vector>
#include<string>
using namespace std;
class Solution
{
public:
string mostCommonWord(string paragraph, vector<string>& banned)
{
unordered_set<string> bannedSet;//定义set 存放禁用单词
for (auto& word : banned)
{
bannedSet.emplace(word);//防止重复
}
int maxnum = 0;
unordered_map<string, int> base_map;//存放被筛选后的字符串
string word;//临时存放
int len = paragraph.size();//计算字符串长度
for (int i = 0; i <= len; ++i)
{
if (i < len && isalpha(paragraph[i]))//isalptha判断是否是字母,同来划分字符串单词 只有字母才行
{
word.push_back(tolower(paragraph[i]));
}
else if (word.size() > 0)//遇到除字母以外的 就将word的值插入map中
{
if (!bannedSet.count(word))
{
base_map[word]++;//相同计数值加1
maxnum = max(maxnum, base_map[word]);
}
word = "";//置空
}
}
int num;
string port_word = "";
for (const auto& n : base_map)//打印
{
if (n.second == maxnum)
{
port_word = n.first;
break;
}
}
return port_word;
}
};
int main()
{
Solution sb;
string a = "i am a boy,i love my country";
vector<string> b = {"am"};
string s=sb.mostCommonWord(a, b);
cout << s << endl;
return 0;
}