#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; }