1. 程式人生 > >LintCode 1484: The Most Frequent Word (練習C++ string, map和set)

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