PAT1071. Speech Patterns (25)
题目要求的Word定义 Here a "word" is defined as a continuous sequence of alphanumerical characters separated by non-alphanumerical characters or the line beginning/end. 所以 can""can""can 中应该是3个单词
#include <iostream> #include <cctype> #include <map> using namespace std; map<string,int> m; void trims(string &s){ int isFront=1,isBack=1; for(int i=0;i<s.size();i++) { if(isFront){ if(!isalnum(s[i])) { s.erase(s.begin()+i); i--; } else isFront=0; } } for(int i=s.size()-1;i>=0;i--){ if(isBack){ if(!isalnum(s[i])){ s.erase(s.begin()+i); } else isBack=0; } } } int main() { string s; int c=0; while(cin>>s){ for(int i=0;i<s.size();i++) { s[i]=tolower(s[i]); } c++; trims(s); int i;string s1; while(!s.empty()){ int len=s.size(); for(i=0;i<s.size();i++){ if(!isalnum(s[i])) break; } if(i!=len) { s1=s.substr(0,i); trims(s1); s=s.substr(i); trims(s); }else{ s1=s; } if(!s1.empty()) m[s1]++; if(i==len) break; } } map<string,int>::iterator ii=m.begin(); int max=-1; string key; while(ii!=m.end()){ if(ii->second>max){ max=ii->second; key=ii->first; }else if(ii->second==max){ if(key>ii->first){ key=ii->first; } } ii++; } cout<<key<<" "<<max<<endl; return 0; }