【STL+暴力枚举】Compound Words UVA - 10391

【STL+暴力枚举】Compound Words UVA - 10391

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
zebra
Sample Output
alien
newborn

题意:
由两个单词组合在一起的叫做组合词,给一系列单词,判断哪些是组合词,并输出。

思路:
用set储存单词,如何判断某单词是否是组合词呢?对于每一个单词,枚举分割点(从0-len-1),然后判断前后两个单词有没有出现过。

PS:
C++中substr函数的用法

  1. 用途:一种构造string的方法

  2. 形式:s.substr(pos, n)

  3. 解释:返回一个string,包含s中从pos开始的n个字符的拷贝(pos的默认值是0,n的默认值是s.size() - pos,即不加参数会默认拷贝整个s)

  4. 补充:若pos的值超过了string的大小,则substr函数会抛出一个out_of_range异常;若pos+n的值超过了string的大小,则substr会调整n的值,只拷贝到string的末尾

AC代码:

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <set>
#include <iterator>
#include <string>

using namespace std;
set<string> s;
set<string>::iterator it;

int main()
{
    string str, s1, s2;
    while(cin>>str)
        s.insert(str);
    for(it = s.begin(); it != s.end(); it++)
    {
        str = *it;
        int len = str.length();
        for(int beg = 0; beg < len - 1; beg++)
        {
            s1 = str.substr(0, beg + 1);
            s2 = str.substr(beg + 1, len - 1);
            if(s.find(s1) != s.end() && s.find(s2) != s.end())
            {
                cout<<str<<endl;
                break;
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/floraqiu/article/details/81209457
今日推荐