题234.pat甲级练习-1071 Speech Patterns (25 分)
一、题目
二、题解
本题要你统计给的语句中出现单词的次数,输出出现次数最大的单词以及次数。需要注意的是本题给出的单词的定义,只有由0-9,a-z,A-Z组成的字符串才叫做单词。所以不妨按如下思路处理:
①用while带着cin去每次输入一个不带空格的字符串(当不再输入时即整条语句输入结束)
②然后在循环体里面处理那个不带空格的字符串–我们去遍历那个字符串,用last记录上一次出现非单词字符的位置(开始last=0),然后当又遍历到非单词字符时,用上一次位置到本次位置来做一次子串截取,这个子串便是本题所说的单词(切记不能直接删除那些非单词字符,然后把最后剩下的整个字符串当作一个合法的单词,这样会使得测试点2错误,因为非单词字符都是应当作单词与单词的分隔符来看待),然后将事先定义的map对应单词个数++(可能出现空串,不用++)。
③对于上一步操作,由于会剩下last到原字符串结尾的子串没有作次数更新,所以在遍历循环结束的时候需补更新一次(可能出现空串)
④输入结束,即while循环结束,求最大次数对应的单词,按题意要求输出即可。
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e6+48576;
string words[maxn];
int cnt;
map<string,int> m;
int main()
{
while(cin>>words[cnt])
{
int last=0;
for(int i=0;i<words[cnt].length();)
{
if(words[cnt][i]>='A'&&words[cnt][i]<='Z')
{
words[cnt][i]=(char)(words[cnt][i]+32);
}
if(!(words[cnt][i]>='0'&&words[cnt][i]<='9'||words[cnt][i]>='a'&&words[cnt][i]<='z'))
{
string temp=words[cnt].substr(last,i-last);
last=i+1;
if(temp!="")
{
m[temp]++;
}
}
i++;
}
string temp=words[cnt].substr(last,words[cnt].length()-last);
if(temp!="")
{
m[temp]++;
}
}
string res;
int maxnum=0;
for(auto it=m.begin();it!=m.end();it++)
{
if(it->second>maxnum)
{
maxnum=it->second;
res=it->first;
}
}
cout<<res<<" "<<maxnum;
}