819. Most Common Word

class Solution {
public:
    string mostCommonWord(string paragraph, vector<string>& banned) {
        unordered_set<string> s(banned.begin(), banned.end());
        unordered_map<string, int> m;
        int idx = 0;
        
        while (true) {
            string t = getLowerWord(paragraph, idx);
            if (t.length() == 0)    break;
            if (s.find(t) == s.end())
                m[t]++;
        }
        
        string res;
        int curmax = 0;
        for (const auto & it : m) {
            if (it.second > curmax) {
                curmax = it.second;
                res = it.first;
            }
        }
        return res;
    }
    string getLowerWord(const string &p, int &idx) {
        while (idx < p.length() && !isalpha(p[idx]))
            idx++;
        string res;
        while (idx < p.length() && isalpha(p[idx])) {
            res.push_back(tolower(p[idx]));
            idx++;
        }
        return res;
    }
};

 

posted @ 2018-11-20 00:15  JTechRoad  阅读(98)  评论(0编辑  收藏  举报