POJ之路12--3080,1936

本文介绍了解决字符串匹配问题的方法,包括暴力搜索最长公共子串和判断一个字符串是否包含在另一个字符串中的两种实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、3080

字符串类型的题目,直接暴力搜索的,为了方便,直接利用的string类型来处理。

思路是:对m个string,首先,将str[0]与str[1]匹配找到最大的共同序列,seq_temp, 然后查找seg_temp和str[2]的最大共同序列,seq_temp1,依次继续下去,找到seq_temp和最后一个str的共同序列,此即结果字符串。

编译测试后的第一版代码,提交时出现超出内存限制,结果在准备修改时,发现调试一句代码忘记注释了。注释掉

ifstream cin("data.txt");
这句测试数据用的代码,再次提交,发现ac了,又是粗心导致没有一次ac,代码如下:

#include<iostream>
#include<string>
#include<fstream>
using namespace std;

string longseq(string st1,string st2)
{
	int count=0,count_temp=0;
	string str,str_temp;
	for(int i=0;i<60;i++)
	{
		for(int j=0;j<60;j++)
		{	
			count_temp=0;
			str_temp="";
			while(i<60&&j<60&&st1[i]==st2[j])
			{
				str_temp+=st1[i];
				count_temp++;
				i++;j++;
			}
			if(count_temp>=3&&count_temp>count)
			{
				count=count_temp;
				str=str_temp;
			}
			if(count_temp==count)
			{
				if(str_temp<str)
					str=str_temp;
			}
			i=i-count_temp;
			j=j-count_temp;		
		}
	}
	return str;
}

int main()
{
	//ifstream cin("data.txt");
	string st[11];int flag=0;
	int n,m,i;
	cin>>n;
	while(n--)
	{
		cin>>m;flag=0;
		for(i=0;i<m;i++)
		{
			cin>>st[i];
		}
		string st_seq=st[0];
		for(i=1;i<m&&flag==0;i++)
		{
			string seq_temp=longseq(st_seq,st[i]);
			if(seq_temp.length()<3)
				flag=1;
			st_seq=seq_temp;
		}
		if(flag==1)
			cout<<"no significant commonalities"<<endl;
		else
			cout<<st_seq<<endl;
	}
	return 0;
}

最后查看别人代码时,发现利用strstr函数会提高效率,之前不知道这个函数,以后处理可以试试。

二、poj1936

判断一个字符串是否包含在另一个中,挺简单的一个题,还是错了好几次,代码如下:

#include<iostream>
#include<string>
#include<fstream>
using namespace std;

int main()
{
//	ifstream cin("data.txt");
	char a[100001],b[100001];
	long i,j;
	while(cin>>a>>b)
	{		
		j=0;i=0;
		while(a[i]&&b[j])
		{
			if(a[i]==b[j])
			{
				i++;j++;
			}
			else 
				j++;
		}
		if(i==strlen(a))
			cout<<"Yes"<<endl;
		else
			cout<<"No"<<endl;
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值