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