819. 最常见的单词

原题链接:819. 最常见的单词

solution:

class Solution {
public:

    string lower(string str) {  //将字符串转换为小写
        for (int i = 0; i < str.size(); ++i)
            str[i] = tolower(str[i]);
        return str;
    }
    string mostCommonWord(string paragraph, vector<string>& banned) {
        int n = paragraph.size();
        int m = banned.size();
        int res = 0;
        string maxstr;  //出现最大次数的单词
        unordered_map<string,int> map1; //存储单词出现的次数
        unordered_map<string,int> map2; //存储禁止出现的单词
        for(auto &x : banned) map2[x]++;

        for(int i = 0,j = 0;i < n && j < n;){
            while(j < n && paragraph[j]!=' ' && isalpha(paragraph[j])) j++;
                string str = lower(paragraph.substr(i,j - i));
                if(!map2.count(str)){   //如果单词没有被禁用
                    map1[str]++;
                    if(res < map1[str]){
                        res = map1[str];
                        maxstr = str;
                    }
                }
                if(!isalpha(paragraph[j]) && paragraph[j] != ' ') j++;  //去掉逗号等
                while(j < n && !isalpha(paragraph[j])) j++;    //去掉空格,将j移动到下一个单词开头
                i = j;  //i也移动
        }
        return maxstr;
    }
};

//上面那个太麻烦重写了一次

class Solution {
public:
    string mostCommonWord(string paragraph, vector<string>& banned) {
        unordered_map<string,int> map1;
        unordered_set<string> map2;

        for(auto &x : banned) map2.insert(x);   //插入
        string word = "";
        for(auto &y : paragraph){
            y = tolower(y);
            if (isalpha(y)) word += y;
            else{
                if(word.size()){
                    if(!map2.count(word)) map1[word]++;
                    word.clear();
                }
            }
        }
        if(word.size() && !map2.count(word)) map1[word]++;

        //遍历哈希表
        string res;
        for(auto &[k,v] : map1){
            if(map1[res] < v){
                res = k;
            }
        }
        return res;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值