不同单词个数统计

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

                                                                                      时间限制: 1 Sec  内存限制: 512 M

题目描述


编写一个程序,输入一个句子,然后统计出这个句子当中不同的单词个数。例如:对于句子“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

思路:这道题解法很多,你可用sscanf来做,也可用c++的string特性。


第一种解法:

#include<stdio.h>
#include<string.h>
#define M 1000000
char b[100000][100];
int main()
{
    int i,lenth,h,k;
    char a[M],ch[100];
    gets(a);
    lenth=strlen(a);
    h=k=0;
    while(h<lenth)
    {
        sscanf(a+h,"%s",ch);
        h+=strlen(ch)+1;
        for(i=0; i<k; i++)
            if(!strcmp(b[i],ch)) break;
        if(i==k) strcpy(b[k++],ch);
        for(i = h; a[i] ==' '; i++)   //空格
            h++;
    }
    //printf("%d\n",k);
    int count, m = 0;
    for(count = 0; count < lenth; count ++)
        if(a[count] ==' ')
            m ++;
    if(m == lenth)
        printf("0\n");
    else
        printf("%d\n", k);
    return 0;
}


第二种解法:

#include<iostream>
#include<sstream>
#include<string>
#include<set>
using namespace std;
int main()
{
    set<string> ans;
    string ss;
    getline(cin,ss);
    stringstream temp;
    temp<<ss;
    string s;
    while(temp>>s)
    {
        ans.insert(s);
    }
    cout<<ans.size()<<endl;
    return 0;
}
第三种解法:

(别人写的比较好的代码)

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






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值