【Leetcode_easy】819. Most Common Word

时间:2023-02-15 06:21:44

problem

819. Most Common Word

solution:

class Solution {
public:
    string mostCommonWord(string paragraph, vector<string>& banned) {
        unordered_map<string, int> m;
        string word = "";
        for(int i=0; i<paragraph.size(); )
        {
            string word = "";
            while(i<paragraph.size() && isalpha(paragraph[i])) 
            {
                word.push_back(tolower(paragraph[i]));
                i++;
            }
            while(i<paragraph.size() && !isalpha(paragraph[i])) i++;
            m[word]++;
        }
        for(auto x:banned) m[x] = 0;
        int num = 0;
        string res = "";
        for(auto x:m)
        {
            if(x.second >num)
            {
                num = x.second;
                res = x.first;
            }
        }
        return res;
    }
};

 

参考

1. Leetcode_easy_819. Most Common Word;

2. Grandyang;

3. Discuss;