Compound Words Time Limit: 5 Seconds Memory Limit: 32768 KB 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.
Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 120,000 words.
Your output should contain all the compound words, one per line, in alphabetical order.
a
alien Source: University of Waterloo Local Contest 1996.09.28 |
先将单词放入字符串集合中,再对于所有单词s,将其分为所有可能的字符串t1,t2,在字符串集合中找是否有t1,t2
要会使用函数substr(),会方便很多
#include<iostream>
#include<string>
#include<set>
using namespace std;
int main(void){
string s,t1,t2;
int i,len;
set<string> sset;
while(cin>>s)
sset.insert(s);
for(set<string>::iterator it=sset.begin();it!=sset.end();it++){
s=*it;
len=s.length();
for(i=0;i<len-1;i++){
t1=s.substr(0,i+1);
t2=s.substr(i+1,len-1);
if(sset.find(t1)!=sset.end()&&sset.find(t2)!=sset.end()){
cout<<s<<endl;
break;
}
}
}
return 0;
}