ACM复合词

10391 Compound Words

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

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

set <string> v;//set容器

int main()
{
	string st;
	set <string>::iterator p;//迭代器
	while(cin>>st)
		v.insert(st);
	for(p=v.begin();p!=v.end();p++){
		st=*p;
		for(int i=0;i<st.length()-1;i++)
		{
			string sub1=st.substr(0,i+1);
			string sub2=st.substr(i+1,st.length()-(i+1));
			if( v.find(sub1)!=v.end() && v.find(sub2 )!=v.end() )//查找
			{
				printf("%s
",st.c_str());
				break;
			}
		}
	}
	return 0;
}

  

zebra

Sample Output

alien

newborn

解题思路:在这个题目中我们需要建立一个set容器,我们每输入一个字符串就用insert()函数将这个字符串存入我们建立的set容器中。我们建立一个迭代器p(相当于一个指针)。通过一个for循环将容器中的每一个字符串都拿出来;又建立一个for循环,在每次循环中利用两次substr()函数将这个字符串拆成两个字符串,然后利用find()函数来查找在这个容器中有没有存在这两个字符串,只有当这两个字符串都存在时,才满足题目要求的条件。最后输出满足条件的字符串。
程序设计:
原文地址:https://www.cnblogs.com/xinxiangqing/p/4668433.html