lintcoe 频率最高的词

lintcode 频率最高的词

描述

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

样例

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

思考

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

代码

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;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_40147449/article/details/88792057