HDU 2072 单词数 题解

HDU 2072 单词数 题解

单词数

Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 22457 Accepted Submission(s): 5433


Problem Description
lily的好朋友xiaoou333最近很空,他想了一件没有什么意义的事情,就是统计一篇文章里不同单词的总数。下面你的任务是帮助xiaoou333解决这个问题。


Input
有多组数据,每组一行,每组就是一篇小文章。每篇小文章都是由小写字母和空格组成,没有标点符号,遇到#时表示输入结束。


Output
每组只输出一个整数,其单独成行,该整数代表一篇文章里不同单词的总数。


Sample Input
you are my friend
#


Sample Output
4

题意就很简单了。计算没有重复的单词数量。我的做法是按位遍历,遇到字母串就记录字母串到temp里面,存到一个字符串数组中。

遇见新的单词与已经存放的单词对比如果没有重复就加入。这里要考虑的是最后。比如 "abc def"在遍历结束后最后再加一次判断def是否重复

本题主要是输入一行的函数fgets(char*,MAXNLENGTH,stdin)函数的使用,也可以使用getline或者cin.getline使用方法可以百度

我仅介绍fgets的使用方法char*就是char数组的头,MAXLENGTH是最大输入的量,stdin是控制台

由fgets输入得到的字符串的\0前面还有一个\n所以需要把这个\n改成 \0 str[strlen(str)-1] = '\0';

然后就是cctype或者ctype.h头文件的函数里面有isalpha(char)判断是不是字母isdigit(char)判断是不是数字还有其他的一些函数这里就介绍两个 其他的可以度娘 谷歌

HDU2072.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cctype>
#include <queue>
using namespace std;
#define MAXN 500
#define MAX 100
char str[MAXN]; //读取的一行的字符串
char svstr[MAXN][MAX];//储存每个已搜索到的单词
char temp[MAXN]; //暂时储存正在搜索的单词的字母
int main()
{
    while(fgets(str,MAXN,stdin),str[0] != '#')
    {
        str[strlen(str)-1] = '\0';
        int w = 0;
        int ok = 0;
        int l = 0;
        for(int i = 0;i < strlen(str);i++)
        {
            if (isalpha(str[i]) && !ok)
            {
                temp[l++] = str[i];
                ok = 1;
            }
            else if (isalpha(str[i])&& ok)
            {
                temp[l++] = str[i];
            }
            else if (!isalpha(str[i]) && ok)
            {
                temp[l++] = '\0';
                int cf = 0;
                for(int j = 0;j < w;j++) //遍历svstr数组检查和搜索到的新单词有没有重复
                {
                    if (!strcmp(temp,svstr[j]))
                    {
                        cf = 1;
                        break;
                    }
                }
                if (cf == 0) //没重复就存进去然后单词数量+1
                {
                    strcpy(svstr[w++],temp);
                }
                ok = 0;
                l = 0;
            }
        }
        if (ok)
        {
            temp[l++] = '\0';
            int cf = 0;
            for(int j = 0;j < w;j++)
            {
                if (!strcmp(temp,svstr[j]))
                {
                    cf = 1;
                    break;
                }
            }
            if (cf == 0)
            {
                strcpy(svstr[w++],temp);
            }
            ok = 0;
            l = 0;
        }
        printf("%d\n",w);
        //printf("%s\n",str);
    }
    return 0;
}

你可能感兴趣的:(HDU 2072 单词数 题解)