//在(lengthA * lengthB)的矩阵中,获取从 k 开始的斜线长度 intGetObliqueLength(bool matrix[][100001], int lengthA, int lengthB, int k) { //初始化 bool ObliqueLine[100001]; //斜线 int cnt = 0; //斜线长度 int x, y; //开始的(x, y)坐标
if (k < 0) //在左下部分 { x = -k; y = 0; } else { //在右上部分或为对角线 x = 0; y = k; } //获取斜线 while (x < lengthA && y < lengthB) { ObliqueLine[cnt++] = matrix[x++][y++]; } //计算最长连续斜线长度 int length = 0; //连续斜线长度 int MaxLength = 0; //最长连续斜线长度 for (int i = 0; i < cnt; i++) { if (ObliqueLine[i] == false) //不连续 { MaxLength = max(length, MaxLength); //更新最长连续斜线长度 length = 0; //连续斜线长度归零 continue; } length++; //连续斜线长度增加 } returnmax(length, MaxLength); //返回最长连续斜线长度 }
//获取最长公共子串的长度 //Longest Common Subsequence intGetLCSLength(string &strA, string &strB) { int lengthA = strA.length(); int lengthB = strB.length(); //转换为矩阵 bool matrix[lengthA][100001]; for (int i = 0; i < lengthA; i++) { for(int j = 0; j < lengthB; j++) { matrix[i][j] = strA[i] == strB[j]; } } //找到最长连续斜线 int max = 0; for (int i = -lengthA + 1; i < lengthB; i++) { int length = GetObliqueLength(matrix, lengthA, lengthB, i); max = (length > max) ? length : max; } return max; }