对题目是理解的,就是处理方式过于复杂,并且最后答案都是错误的。
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<string>
#include<map>
#include<algorithm>
using namespace std;
bool isSet(char temp){
if((temp>='0'&&temp<='9')||(temp>='a'&&temp<='z')||(temp>='A'&&temp<='Z'))return true;
return false;
}
int main(){
#ifdef JUDGE_ONLINE //吸取教训吧,吐血了,ONLINE_JUDGE
#else
freopen("1.txt","r",stdin);
#endif
string str;
map<string,int> cor;
getline(cin,str);
int left,right,len,maxcur=0,i; //left,right用来记录单词首尾,这样考虑复杂化了。
len=str.length();
for(i=0;i<len;i++){
if(isSet(str[i])){
if(i==0||!isSet(str[i-1]))left=i;
}else{
if(i!=0&&isSet(str[i-1])){
right=i-1;
string s=str.substr(left,right-left+1);
if(s[0]>='A'&&s[0]<='Z')s[0]=s[0]+32;
if(cor.find(s)!=cor.end())cor[s]++;
else cor[s]=1;
maxcur=max(maxcur,cor[s]);
}
}
}
if(isSet(str[i-1])){
right=i-1;
string s=str.substr(left,right-left+1);
if(s[0]>='A'&&s[0]<='Z')s[0]=s[0]+32;
if(cor.find(s)!=cor.end())cor[s]++;
else cor[s]=1;
maxcur=max(maxcur,cor[s]);
}
map<string,int>::iterator it;
for(it=cor.begin();it!=cor.end();it++){
if(it->second==maxcur){
printf("%s %d",it->first.c_str(),maxcur);
break;
}
}
return 0;
}
寻找半天才找到答案全都错误的真正原因:
#ifdef ONLINE_JUDGE
#else
freopen(“1.txt”,“r”,stdin);
#endif
将ONLINE_JUDGE误写成了JUDGE_ONLINE
重新跑了一遍,有一个测试点答案错误,逻辑过于复杂,不想改代码了。
算法笔记:
#include<cstdlib>
#include<iostream>
#include<string>
#include<map>
#include<algorithm>
using namespace std;
bool isSet(char temp){
if(temp>='0'&&temp<='9')return true;
if(temp>='a'&&temp<='z')return true;
if(temp>='A'&&temp<='Z')return true;
return false;
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt","r",stdin);
#endif
map<string,int> count;
string str;
getline(cin,str);
int len=str.length(),i=0;
while(i<len){ //遍历整个字符串
string word;
while(i<len&&isSet(str[i])){ //遍历一个单词
if(str[i]>='A'&&str[i]<='Z'){ //将大写转成小写
str[i]=str[i]+('a'-'A');
}
word+=str[i]; //将字符存储到存储改单词的word中
i++;
}
if(word!=""){ //若word非空,则代表之前已存好有效单词了,那就在map中将其个数加1
if(count.find(word)==count.end())count[word]=1;
else count[word]++;
}
while(i<len&&!isSet(str[i])){ //过滤无效字符
i++;
}
}
string ans;
int MAX=0;
for(map<string,int>::iterator it=count.begin();it!=count.end();it++){ //遍历整个map,将出现次数最多的单词记录下来
if(it->second>MAX){
ans=it->first;
MAX=it->second;
}
}
cout<<ans<<" "<<MAX<<endl;
return 0;
}
这样就无需去记录每个单词的首尾下标,再从字符串中将其抽取出来,过于麻烦!对第一遍写的优化了不少。