Program to find length of longest common substring in C++



Suppose we have two lowercase strings X and Y, we have to find the length of their longest common substring.

So, if the input is like X = "helloworld", Y = "worldbook", then the output will be 5, as "world" is the longest common substring and its length is 5.

To solve this, we will follow these steps −

  • Define an array longest of size: m+1 x n+1.

  • len := 0

  • for initialize i := 0, when i <= m, update (increase i by 1), do −

    • for initialize j := 0, when j <= n, update (increase j by 1), do −

      • if i is same as 0 or j is same as 0, then −

        • longest[i, j] := 0

      • otherwise when X[i - 1] is same as 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

      • Otherwise

        • longest[i, j] := 0

    • return len

Let us see the following implementation to get better understanding −

Example

 Live Demo

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

Input

"helloworld", "worldbook"

Output

5
Updated on: 2020-10-10T12:15:42+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements