HDU 2072 字符串处理(判重)

单词数

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


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

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

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

Sample Input
  
  
you are my friend #
 

Sample Output
  
  
4
 

分析:对字符串进行处理,相同的判重,不同的加入集合,计算集合的大小,就知道一共有多少个不同的字符串了。

这道题的坑爹之处在于空格,前面可能有多个空格,后面可能有多个空格,单词之间可能有多个空格,要对多余的空格进行处理

下面给一些测试用例:

input:

kkkkk

            
    kdfghar    kecc     
 k   y   o 
     k
#


output:

1

0

0

2

3

1


#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<cstdio>
using namespace std;

#define maxn 1000
#define LOCAL

char res[maxn][100];
char tot[maxn];
char temp[100];



int main() {

#ifdef LOCAL
	freopen("ACMinput.txt", "r", stdin);
#endif

	while (cin.getline(tot, maxn)) {
		if (tot[0] == '#') break;
		int pos = 0;
		int len = strlen(tot);
		while (tot[pos] == ' ') pos++;//处理前导空格
		int j, i = 0;
		while (pos < len) {
			sscanf(tot+pos, "%s", temp);
			for (j = 0; j < i; j++)
				if (strcmp(res[j], temp) == 0) //对字符串进行判重
					break;
			if (j == i) strcpy(res[i++], temp);//不与之前的相同,则可以加入
			pos += strlen(temp)+1;
			while (tot[pos] == ' ') pos++;//处理中间的空格
		}
		cout << i << endl;
	}
	

	return 0;
}


STL版(非常简洁,别人基本把工作做好了,直接引用就好了,初学建议自己多练习不要过分依赖库)


#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<set>
#include<cstdio>
#include<sstream>
using namespace std;

#define maxn 1000
#define LOCAL

string tot;
string temp;
set<string> Set;



int main() {

#ifdef LOCAL
	freopen("ACMinput.txt", "r", stdin);
#endif

	while (getline(cin, tot) && tot != "#") {
		Set.clear();
		stringstream str(tot);
		while (str >> temp)
			Set.insert(temp);
		cout << Set.size() << endl;
	}
	

	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值