1185: 零起點學算法92——單詞數
Time Limit: 1 Sec Memory Limit: 32 MB 64bit IO Format: %lldSubmitted: 2531 Accepted: 384
[Submit][Status][Web Board]
Description
BobLee 最近忙着考研,話說某一天當他正在看一篇英語閱讀時,突然想到想去統計下這篇文章不同單詞的個數,由於BobLee很忙,所以想讓你幫忙統計一下
Input
有多組數據,每組一行,每組就是一篇小文章。每篇小文章都是由小寫字母和空格組成,沒有標點符號,遇到#時表示輸入結束。(保證每行不超過1000個字符)
Output
每組只輸出一個整數,其單獨成行,該整數代表一篇文章里不同單詞的總數
Sample Input 
you are very kind
#
Sample Output
4
參考代碼:
Re:先設置一個字符型數組來存儲字符,然后逐一將每一個單詞存到二維數組中。接着排序,然后統計不同即可
#include<stdio.h> #include<string.h> #include<stdlib.h> #define maxn 10001 char paper[maxn][100]= {'\0'}; char str[maxn]= {'\0'}; int cmp(const void *a,const void *b) { return strcmp((char *)a,(char *)b); } int main() { int i,count,k; int flag; while(gets(str),*str!='#') { flag=1; count=-1; memset(paper,'\0',sizeof(paper)); for( i=0 ; str[i]!='\0' ; i++ ) { if(flag&&str[i]!=' ') { flag=0; count++; k=0; } else if(flag==0&&str[i]==' ') { flag=1; continue; } if(str[i]!=' ') { paper[count][k++]=str[i]; } } memset(str,'\0',sizeof(str)); //for(i=0;i<=count;i++) //puts(paper[i]); if(count>0) qsort(paper,count+1,100*sizeof(char),cmp); /* for(i=0;i<=count;i++) puts(paper[i]); */ int sum=1; for(i=1; i<=count; i++) { if(strcmp(paper[i-1],paper[i])!=0) sum++; } if(count==-1) sum=0; printf("%d\n",sum); } return 0; }
2.map
1 # include <iostream> 2 # include <map> 3 # include <sstream> 4 # include <string> 5 6 using namespace std; 7 8 int main(){ 9 10 map<string,bool> p; 11 string line; 12 while(getline(cin,line)&&line[0]!='#'){ 13 p.clear(); 14 stringstream ss;//創建一個字符串流 15 ss<<line;//把讀取的數據方法哦字符串流中 16 string word; 17 while(ss>>word){ 18 p[word] = true; 19 } 20 cout<<p.size()<<endl; 21 } 22 23 return 0; 24 }
3.set
1 # include <iostream> 2 # include <string> 3 # include <set> 4 # include <sstream> 5 6 using namespace std; 7 int main(){ 8 9 set<string> s; 10 string line; 11 12 while(getline(cin,line)&&line[0]!='#'){ 13 stringstream ss; 14 ss<<line; 15 16 string word; 17 while(ss>>word){ 18 s.insert(word); 19 } 20 21 cout<<s.size()<<endl; 22 s.clear(); 23 } 24 25 return 0; 26 }
4.strtok
1 #include<iostream> 2 #include<cstdio> 3 #include<cstdlib> 4 #include<cstring> 5 #include<string> 6 #include<fstream> 7 #include<set> 8 using namespace std; 9 set<string> h; 10 char p[1000005]; 11 int main() 12 { 13 14 while(gets(p)&&p[0]!='#') 15 { 16 h.clear(); 17 char *s=strtok(p," "); 18 while(s!=NULL) 19 { 20 string word=""; 21 word+=s; 22 h.insert(word); 23 s=strtok(NULL," "); 24 } 25 cout<<h.size()<<endl; 26 } 27 28 return 0; 29 }
Re:輸入一行由小寫字母和空格組成的句子,計算相同單詞的個數。 需要注意的幾點:
1) 如果一行句子只有空格,則有0個單詞。
2) 如果一行句子由空格開頭,不能算作單詞個數。
3) 如果兩個單詞之間有n個空格隔開,不能算作單詞個數。
4) 如果句子由n個空格結尾,不能算作單詞個數。
5) 相同的單詞的個數只是一個。