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;//输出 }
阅读全文
0 0
- PAT题解——1071. Speech Patterns (25)
- 【PAT】1071. Speech Patterns (25)
- PAT 1071. Speech Patterns (25)
- PAT 1071. Speech Patterns (25)
- PAT 1071. Speech Patterns (25)
- PAT 1071. Speech Patterns (25)
- PAT 1071. Speech Patterns
- PAT 1071. Speech Patterns
- PAT--1071. Speech Patterns
- PAT 1071. Speech Patterns
- 【PAT】1071. Speech Patterns
- PAT-Speech Patterns (25)
- PAT (Advanced) 1071. Speech Patterns (25)
- PAT A 1071. Speech Patterns (25)
- 1071. Speech Patterns (25)PAT甲级
- PAT-A-1071. Speech Patterns (25)
- 【PAT甲级】1071. Speech Patterns (25)
- Pat(A) 1071. Speech Patterns (25)
- YOLO9000论文阅读笔记(二)
- 神经网络 隐藏层 hidden layer名字的意思
- 如何使用epoll?一个完整的C用例
- 传送门
- spring boot项目如何启动
- PAT题解——1071. Speech Patterns (25)
- hdu6115 最近公共祖先+树的重心优化
- 2017.8.13
- CodeBlocks的常用快捷键
- Jsp、Servlet、Action的区别
- mybatis 引用对象属性映射错误 or could not be found for the javaType (xxx.model) : jdbcType (null) combination.
- 斯坦福大学2017年春季_基于卷积神经网络的视觉识别课程视频教程及ppt分享
- 个人向的前端的坑坑洼洼的记录(1)
- Git-warning: CRLF will be replaced by LF in XXX .