习题5-5 UVa10391-Compound Words

这道题第一眼的思路是将所有单词在输入时就两两配对存入新的数组中,输入完毕后遍历单词数组和复和单词数组,将复合数组中与单词数组相同的部分输出。但是这种方法会超时。所以采用拆分所有单词的方法,看了代码就明白了。

题目链接:UVa 10391

AC代码:

#include <iostream>
#include <string>
#include <set>
using namespace std;

const int maxn = 150000;
string word[maxn];
set<string> words;
set<string> com;

int main() {
	int cnt = 0;
	while (cin >> word[cnt])
		words.insert(word[cnt++]);  //set的count方法很好用,存在set中可以避免数组遍历
	for (int i = 0; i < cnt; i++) {
		for (int j = 0; j < word[i].length(); j++) {
			string a = word[i].substr(0, j + 1);
			string b = word[i].substr(j + 1);  //a,b分别书一个单词的两个部分,若它们都在words中出现过,那么这个单词就是所谓的“复合词”
			if (words.count(a) && words.count(b)) {
				com.insert(word[i]);  //再次存放到set中,去除重复输出
				break;
			}
		}
	}
	for (set<string>::iterator it = com.begin(); it != com.end(); it++)
		cout << *it << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值