动态规划之最长公共子串

面试经常出现问题:

最大子序列http://blog.csdn.net/yangquanhui1991/article/details/51943359

动态规划之最长递增子序列http://blog.csdn.net/yangquanhui1991/article/details/51943000

动态规划之最长公共子串http://blog.csdn.net/yangquanhui1991/article/details/51945211

动态规划之最长公共子序列http://blog.csdn.net/yangquanhui1991/article/details/51942532


 子字符串的定义和子序列的定义类似,但要求是连续分布在其他字符串中。比如输入两个字符串BDCABA和ABCBDAB的最长公共字符串有BD和AB,它们的长度都是2。

Longest Common Substring和Longest Common Subsequence是有区别的

     X = <a, b, c, f, b, c>

     Y = <a, b, f, c, a, b>

     X和Y的Longest Common Sequence为<a, b, c, b>,长度为4

     X和Y的Longest Common Substring为 <a, b>长度为2

    其实Substring问题是Subsequence问题的特殊情况,也是要找两个递增的下标序列

    <i1, i2, ...ik> 和 <j1, j2, ..., jk>使

     xi1 == yj1

    xi2 == yj2

    ......

    xik == yjk

    与Subsequence问题不同的是,Substring问题不光要求下标序列是递增的,还要求每次

   递增的增量为1, 即两个下标序列为:

   <i, i+1, i+2, ..., i+k-1> 和 <j, j+1, j+2, ..., j+k-1>

    类比Subquence问题的动态规划解法,Substring也可以用动态规划解决,令

    c[i][j]表示Xi和Yi的最大Substring的长度,比如

   X = <y, e, d, f>

   Y = <y, e, k, f>

   c[1][1] = 1

   c[2][2] = 2

   c[3][3] = 0

   c[4][4] = 1

   动态转移方程为:

   如果xi == yj, 则 c[i][j] = c[i-1][j-1]+1

   如果xi ! = yj,  那么c[i][j] = 0

   最后求Longest Common Substring的长度等于

  max{  c[i][j],  1<=i<=n, 1<=j<=m}

 完整的代码如下:

#include <iostream>
#include <string>


using namespace std;


//暴力法
int longestSub(const string& str1, const string& str2)
{
	int len1 = str1.size();
	int len2 = str2.size();
	if ((len1 == 0) || (len2 == 0))
		return 0;

	// the start position of substring in original string
	int start1 = -1;
	int start2 = -1;

	// the longest length of common substring
	int longest = 0;
	for (int i = 0; i < len1; i++)
	{
		for (int j = 0; j < len2; j++)
		{
			int length = 0;
			int m = i;
			int n = j;
			while (m < len1&&n < len2)
			{
				if (str1[m] != str2[n])
					break;
				++length;
				++m; 
				++n;
			}
			if (longest < length)
			{
				longest = length;
				start1 = i;
				start2 = j;
			}
		
		}
	}

	return longest;
}

//动态规划法
int longestSub_LCS(const string& str1, const string& str2)
{
	int m = str1.size();
	int n = str2.size();
	if ((m == 0) || (n == 0)) return 0;
	int c[100][100] = { 0 };

	for(int i = 1; i <= m; i++)
		c[i][0] = 0;
	for (int j = 1; j <= n; j++)
		c[0][j] = 0;
	c[0][0] = 0;
	int max = -1;
	for (int i = 1; i <= m; i++)
	{
		for (int j = 1; j <= n; j++)
		{
			if (str1[i - 1] == str2[j - 1])
				c[i][j] = c[i - 1][j - 1] + 1;
			else
				c[i][j] = 0;
			if (max < c[i][j])
				max = c[i][j];
		}
	}
	return max;
}

int main()
{
	string str1("YXXXXXY");
	string str2("YXYXXXXZ");
	cout << longestSub(str1, str2) << endl;
	cout << longestSub_LCS(str1, str2) << endl;
	system("pause");
	return 0;
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值