本題雖然是水題,但是我還是比較喜歡做的,能鍛煉思維,比較類似於編譯原理的詞法分析。 題意是要統計一段文章出現頻率最高的單詞。用map<string,int>統計即可。 另外題目要求按照字典序排列,但是好像Map已經有這個功能了,所以就不寫了。 [cpp] #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <algorithm> #include <stack> #include <queue> #include <map> using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); #endif char word[122]; string a; map<string,int> m; int max = 1; while(scanf(" %s",word)!=EOF) { a.clear(); int flag = 0; for(int i=0; i<strlen(word); i++) { if(isalpha(word[i]) || (word[i]>='0' && word[i]<='9')) { flag = 1; if(word[i]>='A' && word[i]<='Z') { word[i] += 32; } a.push_back(word[i]); } else if(flag == 1) { if(m.find(a) == m.end()) { m.insert(make_pair(a,1)); } else { m[a]++; if(m[a]>max) { max = m[a]; } } a.clear(); flag = 0; } } if(flag == 1) { if(m.find(a) == m.end()) { m.insert(make_pair(a,1)); } else { m[a]++; if(m[a]>max) { max = m[a]; } } } } printf("%d occurrences\n",max); for(map<string,int>::iterator i = m.begin();i!=m.end();i++) { if(i->second == max) { printf("%s\n",i->first.c_str()); } } return 0; } 與上題一樣,我直接用上題的代碼A掉。 [cpp] #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <algorithm> #include <stack> #include <queue> #include <map> using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); #endif char word[122]; string a; map<string,int> m; int max = 1; while(scanf(" %s",word)!=EOF && strcmp(word,"#")!=0) { a.clear(); int flag = 0; for(int i=0; i<strlen(word); i++) { if(isalpha(word[i]) || (word[i]>='0' && word[i]<='9')) { flag = 1; if(word[i]>='A' && word[i]<='Z') { word[i] += 32; } a.push_back(word[i]); } else if(flag == 1) { if(m.find(a) == m.end()) { m.insert(make_pair(a,1)); } else { m[a]++; if(m[a]>max) { max = m[a]; } } a.clear(); flag = 0; } } if(flag == 1) { if(m.find(a) == m.end()) { m.insert(make_pair(a,1)); } else { m[a]++; if(m[a]>max) { max = m[a]; } } } } www.2cto.com //printf("%d occurrences\n",max); for(map<string,int>::iterator i = m.begin();i!=m.end();i++) { if(i->second == max) { printf("%s\n",i->first.c_str()); break; } } return 0; }