美文网首页
PAT甲级A1071---map的常见用法

PAT甲级A1071---map的常见用法

作者: 1nvad3r | 来源:发表于2020-07-23 16:08 被阅读0次

    1071 Speech Patterns (25分)

    1071
    分析:

    先用transform(str.begin(), str.end(), str.begin(), ::tolower);转为小写,然后遍历截取字符串,统计每个单词出现的次数存在map中。最后遍历map找到出现次数最多的单词。

    C++:
    #include <iostream>
    #include <string>
    #include <map>
    #include <algorithm>
    
    using namespace std;
    
    bool check(char c) {
        if (c >= '0' && c <= '9')return true;
        if (c >= 'a' && c <= 'z')return true;
        return false;
    }
    
    int main() {
        string str;
        getline(cin, str);
        transform(str.begin(), str.end(), str.begin(), ::tolower);
        map<string, int> mp;
        int pos = 0;
        while (pos < str.length()) {
            string word;
            while (pos < str.length() && check(str[pos]) == true) {
                word += str[pos];
                pos++;
            }
            if (word != "") {
                if (mp.count(word) == 0) {
                    mp[word] = 1;
                } else {
                    mp[word]++;
                }
            }
            while (pos < str.length() && check(str[pos]) == false) {
                pos++;
            }
        }
        string res;
        int max = -1;
        for (map<string, int>::iterator iter = mp.begin(); iter != mp.end(); iter++) {
            if (iter->second > max) {
                max = iter->second;
                res = iter->first;
            }
        }
        cout << res << " " << max << endl;
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:PAT甲级A1071---map的常见用法

          本文链接:https://www.haomeiwen.com/subject/fvmclktx.html