复合词UVa10391(STL简单应用)

一、题目

输入一系列由小写字母组成的单词。输入已按照字典序排序(这句话就是个陷阱),且不超过120000个。找出所有的复合词,即恰好由两个单词连接而成的单词。

二、解题思路

要么枚举两两拼接的情况,O(n^2),n这么大肯定会超时。要么枚举每个单词的拆分情况,当单词比较短时,O(n*m),可能可行。

我们用string类型的数组存储这些单词,map记录单词的是否出现,set自动排序并去重。

三、代码

 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<stdbool.h>
 4 #include<string>
 5 #include<set>
 6 #include<map>
 7 #include<algorithm>
 8 using namespace std;
 9 
10 const int maxn = 120000 + 10;
11 string words[maxn];
12 map<string, bool>myhash;
13 set<string>ans;
14 
15 int main()
16 {
17     int cnt = 0;
18     while (cin >> words[cnt])
19     {
20         myhash[words[cnt++]] = true;
21     }
22     for (int i = 0; i < cnt; i++)
23     {
24         for (int j = 0; j < words[i].size() - 1; j++)
25         {
26             string a = words[i].substr(0, j + 1);
27             string b = words[i].substr(j + 1);
28             if (myhash[a] && myhash[b])
29             {
30                 ans.insert(words[i]);    //这里直接输出好像不对,可能出现重复的情况
31             }
32         }
33     }
34     for (set<string>::iterator it = ans.begin(); it != ans.end(); it++)
35         cout << *it;
36     return 0;
37 }

 

转载于:https://www.cnblogs.com/lfri/p/9362441.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值