您的位置:首页 > 其它

HDU 2072单词数

2015-10-05 09:47 375 查看
题目链接: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!='\n')
{
if(c!=' ') s+=c;
while((c=getchar())!=' '&&c!='\n')
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: