1619 - 单词识别
输入一个英文句子,把句子中的单词(不区分大小写)按出现次数按从多到少把单词和次数在屏幕上输出来,要求能识别英文句号和逗号,即是说单词由空格、句号和逗号隔开。
Input
输入有若干行,总计不超过1000个字符。
Output
输出格式参见样例。
Examples
Input
A blockhouse is a small castle that has four openings through which to shoot.
Output
a:2 blockhouse:1 castle:1 four:1 has:1 is:1 openings:1 shoot:1 small:1 that:1 through:1 to:1 which:1
Solution C
#include<stdio.h> #include<string.h> int main() { char a[1001],b[500][30],c[30]; int num[500]; int i=0,j=0,k=0,count,temp; gets(a); while(a[i]!='\0') { if(a[i]>=65&&a[i]<=90) a[i]=a[i]+32; if(a[i]==' '||a[i]==','||a[i]=='.') { b[j][k]='\0'; j++; k=0; } else { b[j][k]=a[i]; k++; } i++; } b[j][k]='\0'; count=j; for(i=0;i<=count;i++) { num[i]=1; } for(i=0;i<=count;i++) { if(b[i][0]=='\0') continue; for(j=i+1;j<=count;j++) { if(strcmp(b[i],b[j])==0) { num[i]++; b[j][0]='\0'; } } } for(i=0;i<=count;i++) { if(b[i][0]=='\0') continue; for(j=i+1;j<=count;j++) { if(strcmp(b[i],b[j])>0) { strcpy(c,b[i]); strcpy(b[i],b[j]); strcpy(b[j],c); temp=num[i]; num[i]=num[j]; num[j]=temp; } } } for(i=0;i<=count;i++) { if(b[i][0]!='\0') { j=0; while(b[i][j]!='\0') { putchar(b[i][j]); j++; } putchar(':'); printf("%d\n",num[i]); } else { i++; } } return 0; }
Solution C++
#include <cstdio> #include <cstring> #include <string> #include <map> using namespace std; int main() { //freopen("data.in", "r", stdin); //freopen("data.out", "w", stdout); char s[1005]; map < string, int > mp; while (gets(s)) { int len = strlen(s); for (int i = 0; i < len; ) { while (s[i] == ' ' || s[i] == '.' || s[i] == ',') ++i; string str = ""; int j = i; while (j < len && s[j] != ' ' && s[j] != '.' && s[j] != ',') str += tolower(s[j++]); if (j != i) ++mp[str]; i = j; } } for (map < string, int >::iterator it = mp.begin(); it != mp.end(); ++it) printf("%s:%d\n", it->first.c_str(), it->second); return 0; }