求两个字符串的最长公共字串(连续)

题目描述:

输入两个字符串,求其的最长的公共的字串,这与最长公共子序列不一样

输出两字符串的最长公共字串

思路一:

从字符串A开始遍历,同时遍历字符串A,找到第一个与当前字符串A相同的字符,此时记下当前的pos,并同时遍历两字符串,

直到找到两字符串不相同的字符,记下其长度,与max比较,大则则将相同的子串copy到max_str中

C++实现

#include <stdio.h>
#include <string.h>
char* longest_str(char* one, char* two)
{
	int i=0, j=0, max=0, m=0;  //m:record the number of equal characters
	int len_one = strlen(one);
	int len_two = strlen(two);
        char *max_str = (char*)malloc(len_one+1);
	memset(max_str, 0, len_one+1);	
	
	for(i=0; i<len_one; i++)
	{
		for(j=0; j<len_two; j++)
		{
			if(one[i]==two[j])  //the first equal character
			{
				for(m=0; one[i+m]==two[j+m]; m++); //m equal characters
				if(m>max)	//compare m and max
				{
					max = m;
					strncpy(max_str, &two[j], m);  //copy m characters
					max_str[m]='\0';
				}
			}
		}
	}	
	return max_str;
}


思路二:

用动态规划的思想解决。

状态方程 为:maxlen = {aux[j], aux[j-1]+1}

实现代码

const char *dpLongestCommonStr(const char *str1, const char *str2)
{
	int xLen = strlen(str1), yLen = strlen(str2);
	int auxArrLen[yLen], auxArrTemp[yLen];
	int i=0, j=0, maxlen=0, pos=0;

	fill(&auxArrLen[0], &auxArrLen[xLen], 0);
	fill(&auxArrTemp[0], &auxArrTemp[xLen], 0);

	for(i=0; i<xLen; i++)
	{
		for(j=0; j<yLen; j++)
		{
			if(str1[i]==str2[j])
			{
				if(j==0)
					auxArrLen[j] = 1;
				else	
					auxArrLen[j] = auxArrTemp[j-1]+1;
				if(auxArrLen[j]>maxlen)
				{
					maxlen = auxArrLen[j];
					pos = j;
				}
			}
		}
		copy(&auxArrLen[0], &auxArrLen[yLen], &auxArrTemp[0]);
		fill(&auxArrLen[0], &auxArrLen[yLen], 0);
	}
	string retStr(&str2[pos-maxlen+1], &str2[pos+1]);
	return retStr.c_str();
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值