欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【TOJ 2327】Compound Words(set以及substr的运用)

程序员文章站 2022-04-22 23:26:28
描述 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 ......

描述

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
born
less
lien
never
nevertheless
new
newborn
the
zebra
样例输出

alien
newborn

题解

其实这道题就是让我们求出一个由两个单词组成的单词,并按照字典序输出。

解决该题的关键在于substr函数和set函数的组合运用,暴力过~

关于substr函数

substr有两种用法:

假设:string s = "0123456789" ;  //下标从0开始

① string a = s.substr(5)               //表示从下标为5的位置开始截取,一直到结尾。

                                                    // a = "56789"

② string b = s.substr(5,3)            //表示从下标为5的位置开始截取,截取三位。

                                                    // 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);                  //将所有单词存入set 
        
    for(it=se.begin();it!=se.end();it++)  //每一个单词依次遍历 
    {
        for(int i=1;i<(*it).size();i++)
        {
            a=(*it).substr(0,i);
            b=(*it).substr(i);
            if(se.count(a)&&se.count(b))
            {
                cout<<(*it)<<endl;
                break;
            }
        }
    }
    return 0;
}