PAT - A1071

1071 Speech Patterns (25point(s))

  • i <= sentence.size()
    • 使得最后一个单词也能进入循环并被加入map映射表中
  • 源码
#include<bits/stdc++.h>

/*
ID   : A1071
TYPE : map
TIME : 2020.3.3
DURANCE :
NOTICE :
*/

using namespace std;

map<string, int> table;

void low(string &S);

int main(void) {
    string sentence, word;
    int left = 0, len = 0;
    bool flag = true; // 开始截取单词
    getline(cin, sentence);
    // i <= sentence.size()
    // 使得最后一个单词也能进入循环并被加入map映射表中
    for (int i = 0; i <= sentence.size(); ++i) {
        if (isdigit(sentence[i]) || isalpha(sentence[i]))  {
            len++;
            // 截取单词模式关闭,遇见alphanumerical character 开启截取
            if (flag == false) {
                left = i;
                flag = true;
            }
        } else if (flag) { // 截取单词模式开启才截取
            flag = false; // 关闭截取单词
            word = sentence.substr(left, len);
            low(word); // transfer to lower case.
            if(table.find(word) == table.end())
                table[word] = 1;
            else table[word]++;
            len = 0;
        }
    }
    string maxword;
    int maxt = 0;
    for (map<string, int>::iterator iter = table.begin(); iter != table.end(); ++iter) {
        if (iter->second > maxt) {
            maxword = iter -> first;
            maxt = iter -> second;
        }
    }
    cout << maxword << " " << maxt << endl;

    return 0;
}

void low(string &S) {
    for (int i = 0; i < S.size(); ++i) {
        if (S[i] >= 'A' && S[i] <= 'Z') {
            S[i] = S[i] - 'A' + 'a';
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/XyLee/p/12401550.html