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
newborn
HINT
没想到更加高效的办法,就是使用set存储字典,用vector存储每一个单词。读入完毕对vector每一个元素中的单词进行分割处理,然后查找set是否有这两个分割的单词,有就输出。输出之后就跳出循环,否则会输出多个相同的单词。
Accepted
#include<iostream>
#include<algorithm>
#include<set>
#include<string>
#include<vector>
using namespace std;
int main()
{
string s, s1, s2;
set<string>str;
vector<string>arr;
while (cin >> s) {
arr.push_back(s);
str.insert(s);
}
for (int i = 0;i < arr.size();i++)
{
for (int j = 1;j < arr[i].length();j++)
{
s1 = arr[i].substr(arr[i].length() - j);
s2 = arr[i].substr(0,arr[i].length() - j);
if (str.count(s1) && str.count(s2)) {
cout << arr[i] << endl;
break;
}
}
}
}