'lintcode 频率最高的词'

@TOC

描述

给出一个字符串s,表示小说的内容,再给出一个list表示这些单词不参加统计,求字符串中出现频率最高的单词(如果有多个,返回字典序最小的那个)

样例

输入: s = “Jimmy has an apple, it is on the table, he like it”
excludeWords = [“a”,”an”,”the”]
输出:”it”

思考

使用map,记录每个不在list中的单词出现的次数,遍历这个map,得到出现次数最多的。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public:
/**
* @param s: a string
* @param excludewords: a dict
* @return: the most frequent word
*/


string frequentWord(string &s, unordered_set<string> &excludewords) {
// Write your code here
map<string, int> res;
int j = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] == ' ' || s[i] == ','){
string temp = s.substr(j, i-j);
j = i+1;
if (s[j] == ' ')
j++;
if (excludewords.find(temp) == excludewords.end())
res[temp]++;
}
}
string temp = s.substr(j, s.length() - j);
if (excludewords.find(temp) == excludewords.end())
res[temp]++;
int M = INT_MIN;
string R;
map<string, int>::iterator it = res.begin();
while (it != res.end()) {
if (it->second > M) {
M = it->second;
R = it->first;
}
it++;
}
return R;
}
};
-------------end of file thanks for reading-------------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值