You are to find all the two-word compound words in a dictionary. A two-word compound word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.
Input
Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 120,000 words.
Output
Your output should contain all the compound words, one per line, in alphabetical order.
Sample Input
a
alien
born
less
lien
never
nevertheless
new
newborn
the
zebra
Sample Output
alien
Input
Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 120,000 words.
Output
Your output should contain all the compound words, one per line, in alphabetical order.
Sample Input
a
alien
born
less
lien
never
nevertheless
new
newborn
the
zebra
Sample Output
alien
newborn
题意:给出若干个单词(<=120000),如果有其中有一个单词可以由另外两个单词拼接而成就输出,输入已按照字典序从小到大排序,输出所有满足的单词,然后按照字典序从小到大排序。
Accepted | |
Time | 40ms |
---|---|
Length | 561 |
Lang | C++ 5.3.0 |
Submitted | 2018-01-12 11:12:04 |
Shared | |
RemoteRunId | 20596355 |
120000个单词,不能枚举所有的组合方式,但是可以枚举每个单词可以分成几种两个单词,一个单词的长度也就是10左右,所以这样枚举的话时间复杂度还是很低的,然后就是查找了,如何查找一个单词是否存在,这里用set恰恰好。网上也有人用hash,O(1)查找也很简单,时间比这种方法快几倍。
hash方法 链接:http://blog.youkuaiyun.com/shuangde800/article/details/7739749
#include <set>
#include <string>
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
set<string> Set;
int main() {
string s1;
ios::sync_with_stdio(false);
while(cin >> s1) {
Set.insert(s1);
}
set<string>::iterator it;
for(it = Set.begin(); it != Set.end(); it++) {
string s = (*it);
int m = s.length();
for(int i = 0; i < m; i++) {
string sl = s.substr(0, i+1);
string sr = s.substr(i+1, m);
if(Set.find(sl) != Set.end() && Set.find(sr) != Set.end()) {
cout << s <<endl;
break;
}
}
}
return 0;
}