题目描述
给定一个段落 (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"不是最终的答案,虽然它出现次数更多,但它在禁用单词列表中。
说明:
1 <= 段落长度 <= 1000.
1 <= 禁用单词个数 <= 100.
1 <= 禁用单词长度 <= 10.
答案是唯一的, 且都是小写字母 (即使在 paragraph 里是大写的,即使是一些特定的名词,答案都是小写的。)
paragraph 只包含字母、空格和下列标点符号!?’,;.
不存在没有连字符或者带有连字符的单词。
单词里只包含字母,不会出现省略号或者其他标点符号。
题目分析
C++ 11中有两种新的关联容器:unordered_set和unordered_map,其内部实现与set和map大有不同,set和map内部实现是基于RB-Tree,而unordered_set和unordered_map内部实现是基于哈希表(hashtable),时间复杂度为O(1)。
在一个unordered_set内部,元素不会按任何顺序排序,而是通过元素值的hash值将元素分组放置到各个槽(bucket),这样就能通过元素值快速访问各个对应的元素,格子的个数通常是 2 的幂,这使我们可以更容易地从哈希值的比特数中选择格子。
初始化方法:
std::unordered_set<string> things {16}; // 16 buckets
std::unordered_set<string> words {"one", "two", "three", "four"};// Initializer list
std::unordered_set<string> some_words {++std::begin(words),std::end(words)}; // Range
std::unordered_set<string> copy_wrds {words}; // Copy constructor
代码
class Solution {
public:
string mostCommonWord(string paragraph, vector<string>& banned) {
unordered_set<string> ban(banned.begin(), banned.end());
unordered_map<string,int> ParaSearch;
string res = "", s = "";
int repetCount = 0;
//这里使用C++自带两个函数,isalpha()和tolower()函数
//如果不是字母,就用空格隔开
for (auto &c : paragraph) c = isalpha(c) ? tolower(c) : ' ';
//C++使用字符串的类
istringstream istring(paragraph);
//将该字符串空格隔开的进行处理
while( istring >> s) {
//如果ban中不存在该字符串且map中对应的重复次数大于最大
if (!ban.count(s) && ++ParaSearch[s] > repetCount){
repetCount = ParaSearch[s];
res = s;
}
}
return res;
}
};