HDU 2072单词数

题目链接:HDU2072

题目意思:求每一行不同单词数

解题思路:利用STL中的set保存取到的单词输出set.size()

Code:

#include<iostream>
#include<ctype.h>
#include<cstdio>
#include<set>
using namespace std;

int main()
{
    set<string> Set;
    char c;
    while((c=getchar())!='#')
    {
      string s="";
       while(c!='
')
       {
           if(c!=' ') s+=c;
           while((c=getchar())!=' '&&c!='
')
               s+=c;
           if(s.length()) Set.insert(s);
               s="";

       }
       cout<<Set.size()<<endl;
       Set.clear();
    }
}

需要注意的是:如果把if(c!=’ ‘) s+=c;中的判断条件去掉,则“ my friend my”输出为3,而不是正确结果2,因为当行首有空格时,错误的解法会把空格(仅为第一个)加进第一个字符串。

若是求每行单词数,不必考虑相同与否,则题目更为简单。

Code:

#include<iostream>
#include<ctype.h>
#include<cstdio>
using namespace std;

int main()
{
    char s[512];
    s[0]=' ';
    while(true)
    {
        gets(s+1);
        int count=0;
        if(s[1]=='#') break;
        for(int i=1;s[i];i++)
            if(isalpha(s[i])&&s[i-1]==' ')
                count++;
        cout<<count<<endl;
    }
}
原文地址:https://www.cnblogs.com/Wu-Shi/p/5410072.html