原题:https://pintia.cn/problem-sets/994805342720868352/problems/994805398257647616
强行过了一波,一开始又是最后一个case没通过,后来发现是最后一个单词只有一个字母且后面没有符号的情况有问题,所以在第二个for后面又加了一个if判断条件,代码可读性比较差,有时间重新写一个版本
#include<string>
#include<map>
#include<iostream>
#include<cctype>
#include<algorithm>
using namespace std;
bool cmp(pair<string,int> p1,pair<string,int> p2)
{
if(p1.second==p2.second)
return p1.first<p2.first;
else
return p1.second>p2.second;
}
int main()
{
string s,ss;
getline(cin,s);
int len=s.size(),start=-1,end=0;
map<string,int> mp;
for(int i=0;i<len;i++)
{
if(s[i]>='A'&&s[i]<='Z')
s[i]=tolower(s[i]);
}
for(int i=0;i<len;i++)
{
if((!isalnum(s[i])&&start!=-1))
{
end=i;
ss=s.substr(start,end-start);
//cout<<ss<<endl;
start=-1;
if(mp.count(ss)==0)
mp[ss]=1;
else
mp[ss]+=1;
continue;
}
if(isalnum(s[i])&&start==-1)
{
start=i;
continue;
}
}
if(start!=-1&&isalnum(s[len-1]))
{
end=len;
ss=s.substr(start,end-start);
//cout<<ss<<endl;
start=-1;
if(mp.count(ss)==0)
mp[ss]=1;
else
mp[ss]+=1;
}
int max=-1;
string temp;
for(map<string,int>::iterator it=mp.begin();it!=mp.end();it++)
{
if(max<it->second)
{
max=it->second;
temp=it->first;
continue;
}
if(max==it->second&&it->first<temp)
{
temp=it->first;
}
}
cout<<temp<<" "<<max<<endl;
return 0;
}