算法提高 不同单词个数统计

来源:互联网 发布:中国崩溃论 知乎 编辑:程序博客网 时间:2024/05/27 09:46
   算法提高 不同单词个数统计

题目描述
编写一个程序,输入一个句子,然后统计出这个句子当中不同的单词个数。例如:对于句子“one little two little three little boys”,总共有5个不同的单词:one, little, two, three, boys。
说明:(1)由于句子当中包含有空格,所以应该用gets函数来输入这个句子;(2)输入的句子当中只包含英文字符和空格,单词之间用一个空格隔开;(3)不用考虑单词的大小写,假设输入的都是小写字符;(4)句子长度不超过100个字符。

输入
输入只有一行,即一个英文句子。
输出
输出只有一行,是一个整数,表示句子中不同单词的个数。
样例输入
one little two little three little boys
样例输出
5
解题思路:此题最好运用set容器,set容器可以计算里面包括的种类,还有注意scanf和gets的不同点是scanf遇到空格和换行,Tab键结束,而gets可以接受空格,遇到换行结束,相同点是gets和scanf读完字符串后会在后面加’\0’;

#include<iostream>#include<stdio.h>#include<string.h>#include<set>using namespace std;int main(){    char ch[105];    gets(ch);    string sh[105];    int len1=strlen(ch);    set<string> S;    int k=0;    int temp=0;    for(int i=0;i<=len1;i++)    {        if(ch[i]==' '||ch[i]=='\0')        {            for(int j=k;j<i;j++)            {                sh[temp]=sh[temp]+ch[j];            }            temp++;            k=i+1;        }    }    for(int i=0;i<temp;i++)        S.insert(sh[i]);    cout<<S.size()<<endl;    return 0;}
1 0
原创粉丝点击