最长连续公共子串算法

简介:
#include <iostream>
#include <string.h>
using namespace std;

int  GetLCSLength(char* str1, char* str2)
{
	int length1 = strlen(str1); 
	int length2 = strlen(str2);
	int maxCommonLen = 0; // 公共子串的长度
	int endIndex = 0;     // 公共子串的最后位置

	// 申请内存
	int** table = new int*[length1];
	for(int i = 0; i < length1; i++)
		table[i] = new int[length2];

	// 初始化td
	for(int i = 0; i < length1; i++)
	{
		for(int j = 0; j < length2; j++)
		{
			table[i][j] = str1[i] == str2[j] ? 1 : 0;
		}
	}
	for(int i = 1; i < length1; i++)
	{
		for(int j = 1; j < length2; j++)
		{
			if(str1[i] == str2[j])// 左上角的元素值加1作为当前值
				table[i][j] = table[i-1][j-1] + 1;
			if(maxCommonLen < table[i][j])
			{
				endIndex = j;// 记录最长公共子串的最后一个字符的下标位置
				maxCommonLen = table[i][j];
			}
		}
	}
	cout << "最长公共子串:";
	for(int i = endIndex-maxCommonLen+1; i <= endIndex; i++)
		cout << str2[i];
	cout << endl;

	// 释放内存
	for(int i = 0; i < length1; i ++)
		delete[] table[i];
	delete[] table;

	return maxCommonLen;
}


int main()
{
	char* str1 = "21232523311324";
	char* str2 = "312123223445";
	char* str3 = "asdfeabcsdfa";
	char* str4 = "difabcdi";

	cout << GetLCSLength(str1, str2) << endl;
	cout << GetLCSLength(str3, str4) << endl;
}

目录
相关文章
|
8月前
|
算法
算法修炼Day52|● 300.最长递增子序列 ● 674. 最长连续递增序列 ● 718. 最长重复子数组
算法修炼Day52|● 300.最长递增子序列 ● 674. 最长连续递增序列 ● 718. 最长重复子数组
|
3月前
最长连续不重复子序列
最长连续不重复子序列
15 1
|
3月前
|
算法
leetcode-128:最长连续序列
leetcode-128:最长连续序列
19 0
|
3月前
leetcode-1438:绝对差不超过限制的最长连续子数组
leetcode-1438:绝对差不超过限制的最长连续子数组
19 0
|
3月前
leetcode-674:最长连续递增序列
leetcode-674:最长连续递增序列
26 0
|
4月前
|
存储 机器学习/深度学习 C语言
Day3 字符串中找出连续最长的数字串、数组中出现次数超过一半的数字
Day3 字符串中找出连续最长的数字串、数组中出现次数超过一半的数字
28 0
|
9月前
1259:【例9.3】求最长不下降序列 2021-01-15
1259:【例9.3】求最长不下降序列 2021-01-15
|
11月前
|
存储 算法
7-181 最长连续递增子序列
7-181 最长连续递增子序列
39 0
|
存储 算法
LeetCode 128. 最长连续序列
LeetCode 128. 最长连续序列
83 0
LeetCode 128. 最长连续序列
leetcode 674 最长连续递增序列
leetcode 674 最长连续递增序列
66 0
leetcode 674 最长连续递增序列

热门文章

最新文章