ZOJ 1825 compoud words

题目大意:输入一串递增的单词序列,需要找出符合条件的单词递增输出,条件是:将一个单词拆成左右两个单词后,能在输入中找到这两个单词。例如单词 alien,可以拆成 a 和 lien,而输入中刚好同时有a和lien,则符合条件,输出alien。又如单词born,无论拆成b和orn,还是bo和rn,亦或是bor和n,都无法在输入中同时找到两个被拆分的单词。

解题思路:把每一个单词拆成两个,然后就看这两个单词是否在输入单词里面。因此可以采用set集合来判断某个单词是否存在输入单词序列里面,用substr分割一个字符串。

 

/*
	ZOJ 1825
	Emerald
	Tue 12 May 2015
*/
#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <set>

using namespace std;

int main() {
	set <string> dict; // a set contains the inputting wotd
	string word;
	while( cin >> word ) {
		dict.insert( word );
	}

	set <string> :: iterator it;
	for( it = dict.begin(); it != dict.end(); it ++ ) {
		for( int i=1; i < it->length(); i++ ) { // it->substr( pos, len ) : split a string from the pos of the origin
											// string, and the splitted string's length is len
			if( dict.count( it->substr( 0, i ) ) && dict.count( it->substr( i, it->length() - i ) ) ) {
				printf( "%s\n", it->c_str() ); // print the compound word
				break; // break, or else this string may be printed again
			}
		}
	}

	return 0;
}

 

posted @ 2015-05-12 20:39  Emerald  阅读(191)  评论(0编辑  收藏  举报