题意:
给出一段语句,求其中出现最多的词。词是被其他字符分隔或在行头、行尾的由字母、数字组成的连续字符串。
解法:
用set保存词,用map保存其中出现的次数。还要用到将大写转化为小写的函数。
总结:
这一题主要是感觉考对字符串操作熟不熟悉,个人对c++的string操作函数不是很熟悉,有的函数是搜索的。这题写得有点繁琐了。
(用时:38:44.51)
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<cstring>
#include<cmath>
//#include<bits/stdc++.h>
using namespace std;
int main()
{
string text;
getline(cin,text);
int b=0,e=0;
transform(text.begin(),text.end(),text.begin(),::tolower);
map<string,int> strMap;
set<string> strSet;
b=-1;
for(int i=0; i<text.length(); i++) {
if(((text[i]>='a'&&text[i]<='z')||(text[i]>='0'&&text[i]<='9'))) {
if(b==-1) {
b=i;
}
if(i==text.length()-1) {
string s= text.substr(b,i-b+1);
strSet.insert(s);
if(strMap.count(s)==0) {
strMap[s]=0;
}
strMap[s]++;
}
} else {
if(b==-1) {
continue;
}
string s= text.substr(b,i-b);
strSet.insert(s);
if(strMap.count(s)==0) {
strMap[s]=0;
}
strMap[s]++;
b=-1;
}
}
set<string>::iterator it;
int maxNum = -1;
string maxNumStr;
for(it = strSet.begin(); it!=strSet.end(); it++) {
if(strMap[*it]>maxNum) {
maxNum = strMap[*it];
maxNumStr = *it;
}
}
cout<<maxNumStr<<" "<<maxNum<<endl;
return 0;
}