使用unordered_map方法查找C++中最(多个)常用词
Finding the most(multiple) common word in C++ using unordered_map approach
从文本输入中查找最常用的单词,不包括给定单词的列表。如果有多个最大字数,则显示所有字数。
我对 21/24 个测试用例的方法词,我似乎想不出我缺少的 3 个测试用例。
我正在添加我现在拥有的代码,据我说这是有效的。我现在不想要另一种实现它的方式(尽管非常欢迎提出建议),我只想就我缺少的可能测试用例挑选你的大脑。
vector<string> mostCommonWord(string paragraph, vector<string>& banned) {
unordered_map<string, int>m;
for(int i = 0; i < paragraph.size();){
string s = "";
while(i < paragraph.size() && isalpha(paragraph[i])) s.push_back(tolower(paragraph[i++])); // go through till you find one word completely
while(i < paragraph.size() && !isalpha(paragraph[i])) i++; // avoid all the white spaces and other characters
m[s]++; // include the word found and increment its count
}
for(auto x: banned) m[x] = 0; // make the count of all the banned words to be 0
vector<string> result;
string res = "";
int count = INT_MIN;
// find the maximum count
for(auto x: m)
if(x.second > count) count = x.second;
// we might have the case where all the words were in banned words, which would result the count == -1, so return an empty vector in this case
if(count <= 0) return result;
// add the words corresponding to that to the final vector<string>
for(auto x: m)
if(x.second == count) result.push_back(x.first);
return result;
}
它适用于我能想到的所有场景,但失败了 3 个测试用例。 我无法访问这些测试用例,只是想讨论一下它可能是什么!
- 您确定其他字符(数字)应被视为单词分隔符吗?
- 如果
paragraph
以空格开头或不是字母字符,则将空字符串插入到映射中:m[""] = 1
.
相关文章:
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 在C++中,如何通过几种类型从元组中选择多个元素
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 使用C++在Qt3D中创建多个视口时出现问题
- 如何从txt文件中读取多个不同长度的数组?
- 如果中的多个语句是否与多个 if 相同?
- Eclipse CDT:单个项目中有多个C++文件
- 如何在生成文件中添加多个标头 (HDR) 和对象?
- 我们是否需要为 C++ 中的多个函数初始化多个模板?
- 即使我没有包含多个文件,C++中的多个定义错误
- 我可以在具有一个标头和一个接口的 cpp 文件中有多个嵌入吗?
- 删除功能不适用于串行通信后多个循环中的多个实例
- 在函数中创建多个lock_guards
- 我应该如何在没有变量的情况下将相同的参数传递给 CMAKE 中的多个目标?
- 如何在Qt中进行多个图形更改时最大程度地减少屏幕闪烁
- 使用unordered_map方法查找C++中最(多个)常用词
- 在外部功能中具有一个变量初始化或内部功能中的多个初始化是最有效的
- 从文件中查找多个总和的最有效方法是什么
- 允许用户在迷宫游戏中最多移动五个空间
- 使用c++在非常大的文本文件(10gb)中搜索多个单词是最快的方式