PAT题解——1071. Speech Patterns (25)

来源:互联网 发布:荷塘月色淘宝论坛上 编辑:程序博客网 时间:2024/06/05 08:15

[声明]:这道题其实大体上和《算法笔记》的思路相同,但是使用了迭代器it对str进行扫描,和《算法笔记》上使用i和str.length()略有区别;不过还是贴出来;
[题目链接]:https://www.patest.cn/contests/pat-a-practise/1071
[解题思路]:使用getline输入string str;并扫描,遇到非数字和字母的符号时将得到的词计入map 映射的count容器中(注意先要调用find看是否已经存在);遍历count寻找最大的词;
[注意点]:由于扫描str的函数中包含了while循环,而这个while循环中也有it++,所以如果it=str.end()而退出此while循环后,注释处直接it++会导致for循环不断继续,最终使得最后一个测试点发生段错误;

#include<cstdio>#include<map>#include<string> #include<iostream>using namespace std;map<string,int> count;int main(){    string str;    getline(cin,str); //输入str     for(string::iterator it=str.begin();it!=str.end();){ //使用迭代器遍历str以找到符合要求的词         string temp; int flag=0;  //temp记录暂时得到的词,flag=0表示没有找到,temp="";         while(it!=str.end()&&(*(it)>='0'&&*(it)<='9')||(*(it)>='a'&&*(it)<='z')||(*(it)>='A'&&*(it)<='Z')){            if(*it>='A'&&*it<='Z') *it=*it-'A'+'a'; //如果是大写转化为小写             temp+=*(it); //链接出完整的词             it++; flag=1; //flag=1表示temp不为空;         }        if(flag){   //如果上面不使用flag,此处也可以换成 if(temp!="") 注意中间没有空格,表示temp不为空             if(count.find(temp)!=count.end()) count[temp]++;            else count[temp]=1;        }        if(it!=str.end()) it++; //如果直接在上面的for循环中使用it++则会导致最后一个测试点段错误     }    int max=0; string k; //最大的次数max,对应的字符串k     for(map<string,int>::iterator it=count.begin();it!=count.end();it++){ //遍历count映射找到最大的count对应的字符 串         if(it->second>max){            k=it->first; //map映射中的string             max=it->second;//map映射中的int         }    }    cout<<k<<" "<<max<<endl;//输出 }
原创粉丝点击