1071 Speech Patterns (25分)
题目链接
1.题意分析:首先给出单词的一个定义:只包含大小写字母和数字组合,其它字符都是无效字符。然后给一个字符串,统计出现次数最多的字符串以及次数。
2.思路分析:首先分割出每一个有效单词,然后利用map进行单词与次数之间的映射。那么单词出现的次数可以这样统计:在得到一个有效的单词之后,首先查找在map里面有没有这个单词,如果存在则次数加1;如果不存在,则次数记为1.至于每一个word可以通过遍历整个字符串,然后如果该字符是有效字符,则将其加入当前单词中;如果该字符不是有效字符则将单词的出现次数加1.之后跳过非有效字符,进行下一个单词的组合。
3.代码时间:
#include <iostream>
#include <map>
#include <string>
using namespace std;
bool check(char c)
{
if(c>='0'&&c<='9')
return true;
if(c>='a'&&c<='z')
return true;
if(c>='A'&&c<='Z')
return true;
return false;
}
int main()
{
map<string,int> count;
string str;
getline(cin,str);//读入整行字符串
int i=0;
while(i<str.size())
{
string word;//定义新单词
while(i<str.size()&&check(str[i])==true)
{
if(str[i]>='A'&&str[i]<='Z')
{
str[i]+=32;//大写转小写
}
word+=str[i];
i++;
}
if(word!="")//单词非空才可以计数
{
if(count.find(word)==count.end())
{
count[word]=1;
}
else
{
count[word]++;
}
}
while(i<str.size()&&check(str[i])==false)
{
i++;//跳过不符合条件的字符
}
}
string ans;
int max=0;
for(map<string,int>::iterator it=count.begin(); it!=count.end(); it++)
{
if(it->second>max)
{
max=it->second;
ans=it->first;
}
}
cout << ans<<' '<<max << endl;
return 0;
}