UVa10391


遍历所有字符串,两两相加然后匹配的解法TLE
所以采用另一种思路,查看每个单词的拆分组合是否已存在于set中
这里用了str.substr(x,n)函数
x 指定字符串起始位置
n 指定复制的字符数长度

TLE代码:

#include <map>
#include<vector>
#include<set>
#include <string>
#include<iostream>
using namespace std;
map<string,int>IDcache;
vector<string>Strcache;
int ID(string s)
{
	if (IDcache.count(s)==1)  return IDcache[s];
	Strcache.push_back(s);
	return IDcache[s] = Strcache.size() - 1;
}

void IsCompound()
{
	
	string temp;
	set<string>ans;
	while (cin >> temp)
	{
		
		int x = ID(temp);
	
		
	}
	int size = Strcache.size();
	
	for (int i = 0; i < size; i++)
		for (int j = i + 1; j < size; j++)
		{
			string temp1 = Strcache[i] + Strcache[j];
			string temp2 = Strcache[j] + Strcache[i];
			int t1 = ID(temp1);
			int t2 = ID(temp2);
			if (t1<=IDcache.size())
			{
				ans.insert(Strcache[IDcache[temp1]]); continue;
			}
			if (IDcache.count(temp2) != 0) {
				ans.insert(Strcache[IDcache[temp2]]);
				
			}
			
		}
	auto it = ans.begin();
	
	while(it!=ans.end())
	{
		
		cout << *it << endl; it++;
	}
}
int main()
{
	IsCompound();
	return 0;
}

AC代码:

#include <iostream>
#include <set>
#include <vector>
#include <iostream>
#include<string>
using namespace std;
vector <string> Str;
set<string>s;
int main()
{
	string temp;
	while (cin >> temp)
	{
		Str.push_back(temp);
		s.insert(temp);
		
	}


	for (int i = 0; i < s.size(); i++)
		for (int j = 1; j < Str[i].size(); j++)
			if (s.count(Str[i].substr(0, j)) && s.count(Str[i].substr(j, Str[i].size() - j)))

			{
				cout << Str[i] << endl; break;//若不break将WE,可能会重复输出
			}


	return 0;
}


参考:https://blog.csdn.net/iboxty/article/details/45958193?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&dist_request_id=1328741.49540.16170815072631933&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值