C++程序:查找最长公共子串的长度


假设我们有两个小写字符串 X 和 Y,我们需要找到它们最长公共子串的长度。

例如,如果输入 X = "helloworld",Y = "worldbook",则输出为 5,因为 "world" 是最长公共子串,其长度为 5。

为了解决这个问题,我们将遵循以下步骤:

  • 定义一个大小为 m+1 x n+1 的数组 longest。

  • len := 0

  • for i := 0 to m do −

    • for j := 0 to n do −

      • if i == 0 or j == 0 then −

        • longest[i, j] := 0

      • else if X[i - 1] == Y[j - 1] then −

        • longest[i, j] := longest[i - 1, j - 1] + 1

        • if len < longest[i, j] then −

          • len := longest[i, j]

          • row := i

          • col := j

      • 否则

        • longest[i, j] := 0

    • 返回 len

让我们来看下面的实现,以便更好地理解:

示例

 在线演示

#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
int solve(char* X, char* Y, int m, int n){
   int longest[m + 1][n + 1];
   int len = 0;
   int row, col;
   for (int i = 0; i <= m; i++) {
      for (int j = 0; j <= n; j++) {
         if (i == 0 || j == 0)
            longest[i][j] = 0;
         else if (X[i - 1] == Y[j - 1]) {
            longest[i][j] = longest[i - 1][j - 1] + 1;
            if (len < longest[i][j]) {
               len = longest[i][j];
               row = i;
               col = j;
            }
         }
         else
            longest[i][j] = 0;
      }
   }
   return len;
}
int main(){
   char X[] = "helloworld";
   char Y[] = "worldbook";
   int m = strlen(X);
   int n = strlen(Y);
   cout << solve(X, Y, m, n);
   return 0;
}

输入

"helloworld", "worldbook"

输出

5

更新于:2020年10月10日

2K+ 浏览量

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.