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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/roufoo/article/details/84717915

原题如下:
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<string> &excludewords) {
        map<string, int> m; //word vs count
        
        int 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 word
                if ((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 string
            if (j > 0) i = j + 1;
            else i++;
        }
        
        return maxCountWord;
    }
};

猜你喜欢

转载自blog.csdn.net/roufoo/article/details/84717915