题解 | #单词识别#
单词识别
https://www.nowcoder.com/practice/16f59b169d904f8898d70d81d4a140a0?tpId=40&rp=1&ru=%2Fta%2Fkaoyan&qru=%2Fta%2Fkaoyan&difficulty=3&judgeStatus=3&tags=579&title=&sourceUrl=&gioEnter=menu
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> typedef struct{ char w[20]; int cnt; }Word; int cmp(const void *a,const void *b){ Word *a1 = (Word *)a; Word *b1 = (Word *)b; if(a1->cnt == b1->cnt)return strcmp(a1->w,b1->w); else return b1->cnt - a1->cnt; } int main() { Word word[1000]; char s[1000]; char tmp[20]; fgets(s, sizeof(s), stdin); s[strcspn(s,"\n")] = '\0'; int i=0; int k=0,idx=0; while(s[i] != '\0'){ int flag = 0; idx = 0; while(s[i] != '\0' && s[i] != ' ' && s[i] != '.'){ tmp[idx++] = s[i++]; } tmp[0] = tolower(tmp[0]); tmp[idx] = '\0'; for(int i=0;i<k;i++){ if(strcmp(tmp,word[i].w) == 0){ flag = 1; word[i].cnt++; break; } } if(!flag){ strcpy(word[k].w,tmp); word[k].cnt = 1; k++; } while(s[i] == ' ' || s[i] == '.')i++; } qsort(word,k,sizeof(Word),cmp); for(int i=0;i<k;i++){ printf("%s:%d\n",word[i].w,word[i].cnt); } return 0; }