PAT (Advanced Level) Practice A1071 Speech Patterns (25 分)(C++)(甲级)(map)

版权声明:假装有个原创声明……虽然少许博文不属于完全原创,但也是自己辛辛苦苦总结的,转载请注明出处,感谢! https://blog.csdn.net/m0_37454852/article/details/86659093

原题链接:A1071 Speech Patterns

#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstring>
#include <map>
using namespace std;
//这里我用了指针,用来修改原字符串(大写转小写)
bool isLegal(char *ch)//判断该字符是否为合法字符
{
    if(*ch >= 'A' && *ch <= 'Z') *ch += 'a' - 'A';//若为大写,则先转化为小写
    if(*ch >= '0' && *ch <= '9') return true;
    if(*ch >= 'a' && *ch <= 'z') return true;
    return false;
}

int main()
{
    map<string, int> Cnt;
    string str, common;
    int first = -1, max_num = 0;
    getline(cin, str);//题目已说明 there is one line of text ,故可用getline输入
    for(int i=0; i<str.length(); i++)
    {
        if(first == -1 && isLegal(&str[i])) first = i;//first保存每个单词首字母所在位置
        if(first != -1 && !isLegal(&str[i]))
        {
            Cnt[str.substr(first, i-first)]++;//该字符计数器增一
            first = -1;//重置标记
        }
    }
    if(first != -1) Cnt[str.substr(first, str.length()-first)]++;//考虑最后一个 例如输入a a应输出a 2
    for(map<string, int>::iterator it = Cnt.begin(); it != Cnt.end(); it++)//最后一个测试用例就是上面这个坑
    {
        if(it->second > max_num)//遍历找出次数最多的输出即可(map自带字典序效果)
        {
            max_num = it->second;
            common = it->first;
        }
    }
    cout<<common<<" "<<max_num<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37454852/article/details/86659093