LintCode 1484: The Most Frequent Word (练习C++ string, map和set)

原题如下:
1484. The Most Frequent word
Give a string s witch represents the content of the novel, and then give a list indicating that the words do not participate in statistics, find the most frequent word(return the one with the smallest lexicographic order if there are more than one word)

Example
Input: s = “Jimmy has an apple, it is on the table, he like it”
excludeWords = [“a”,“an”,“the”]
Output:“it”

我的解法如下:
注意:

  1. string.find(substring, pos) 返回-1 (即string::npos)如果没有找到substring。
  2. 注意要跳过’ ', ',‘和’.'字符。
  3. 有三种情况需要区分:
    a. maxCountWord还没有初始化
    b. 新找到的词的词频已经大于maxCount
    c. 新找到的词的词频等于maxCount,则要比较该词与maxCountWord的大小。
class Solution {
public:/*** @param s: a string* @param excludewords: a dict* @return: the most frequent word*/string frequentWord(string &s, unordered_set &excludewords) {map m; //word vs countint len = s.size();int maxCount = 0;string maxCountWord = "";int i = 0, j = 0;string word;while (i < len) {if (s[i] == ' ') while(s[i++] == ' ');j = s.find(' ', i);if (j != string::npos) {   //if found the ' 'if ((s[j - 1] == ',') || (s[j - 1] == '.')) word = s.substr(i, j - i - 1);else word = s.substr(i, j - i);} else { //it should be the last wordif ((s[len - 1] == ',') || (s[len - 1] == '.')) word = s.substr(i, len - i - 1);else word = s.substr(i, len - i);}if (excludewords.find(word) == excludewords.end()) {if (m.find(word) == m.end()) {m[word] = 1;} else {m[word]++;}if (maxCountWord.size() == 0) {maxCount = m[word];maxCountWord = word;} else if ((m[word] > maxCount)) {maxCount = m[word];maxCountWord = word;} else if (m[word] == maxCount) {if (word < maxCountWord)maxCountWord = word;}}if (j == string::npos) return maxCountWord;   //j = -1, reach the end of the stringif (j > 0) i = j + 1;else i++;}return maxCountWord;}
};


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部