[TOJ 2327] Compound Words (combination Words) (use of set and substr), toj2327
Description
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 shoshould 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
Question
In fact, this question is to let us find a word consisting of two words and output it in Lexicographic Order.
The key to solving this problem lies in the combined use of the substr function and the set function ~
Substr Functions
Substr can be used in two ways:
Suppose: string s = "0123456789"; // subscript starts from 0
① String a = s. substr (5) // It indicates the truncation from the position where the subscript is 5 to the end.
// A = "56789"
② String B = s. substr (5, 3) // It indicates that it is intercepted from the position where the subscript is 5 and three digits are intercepted.
// B = "567"
# Include <string> # include <set> # include <iostream> using namespace std; int main () {string word, a, B; set <string> se; set <string >:: iterator it; while (cin> word) se. insert (word); // save all words to set for (it = se. begin (); it! = Se. end (); it ++) // traverse each word in sequence {for (int I = 1; I <(* it ). size (); I ++) {// split a word into two parts a = (* it ). substr (0, I); // traverse all the letters except the last letter of the word B = (* it ). substr (I); // traverses all the letters except the first letter of the word if (se. count (a) & se. count (B) // If the set contains the combination of these two characters, the output is {cout <(* it) <endl; break ;}} return 0 ;}