Compound Words UVA - 10391(c++用法中substr函数用法+map实现)

题意:

给出字典中一堆单词,单词的输入方式是以字典序输入的。问:在这一堆单词中,有那些单词是通过其它两个单词组合而来的。按字典序升序输出这些单词。

题目:

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

分析:

如果用两个字符串拼接看拼接好的字符串是否在字典中,一定会超时。
我们可以逆向,由于字符串的长度不是很长,所以把一个字符串拆为两个字符串看这两个字符串是否都在字典中即可
在这里我用的map实现+substr函数

c++用法中substr函数用法

#include<string>
#include<iostream>
using namespace std;
int main()
{
string s("12345asdf");
string a = s.substr(0,5);     //获得字符串s中从第0位开始的长度为5的字符串
string b=s.substr(5);/**==string b=s.substr(5,9)*////先有pos,若无n,直接认为是字符串长度
cout << a << endl;
cout << b << endl;
}

  1. 用途:一种构造string的方法
  2. 形式:s.substr(pos, n)
  3. 解释:返回一个string,包含s中从pos开始的n个字符的拷贝(pos的默认值是0,n的默认值是s.size() - pos,即不加参数会默认拷贝整个s)
  4. 先有pos,若无n,直接认为是字符串长度

ac代码

#include<iostream>
#include<string.h>
#include<map>
#include<string>
#include<algorithm>
using namespace std;
const int M=1e6+10;
map<string,int>mp;//使用map对于字典中的单词进行映射,作用就是用于查询单词是否字典中
string s[M];
int k;
int main()
{
    k=0;
    while(cin>>s[k])
    {
        mp[s[k]]=1;k++;
    }
    for(int i=0; i<k; i++)
        for(int j=0; j<s[i].length(); j++)
        {
            string u,v;
            u=s[i].substr(0,j);//然后从第一个开始,将每个单词分成它所能变成的任意两个单词
            v=s[i].substr(j);///substr是C++语言函数,主要功能是复制子字符串,要求从指定位置开始,并具有指定的长度。
            if(mp[u]&&mp[v])//如果分成的两个单词的映射值均为1,那么这个就输出这个单词
            {
                cout<<s[i]<<endl;
                break;
            }
        }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值