C++ Program to Find the Length of Longest Common Substring

This C++ Program finds Length of Longest Common Substring.

Here is source code of the C++ Program to Find Length of Longest Common Substring. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Find Length of Longest Common Substring
  3.  */
  4. #include<iostream>
  5. #include<cstring>
  6. using namespace std;
  7.  
  8. // A utility function to find maximum of two integers
  9. int max(int a, int b)
  10. {
  11.     return (a > b)? a : b;
  12. }
  13.  
  14. /* Returns length of longest common substring of X[0..m-1] and Y[0..n-1] */
  15. int LCSubStr(char *X, char *Y, int m, int n)
  16. {
  17.     int LCSuff[m + 1][n + 1];
  18.     int result = 0;
  19.     for (int i = 0; i <= m; i++)
  20.     {
  21.         for (int j=0; j<=n; j++)
  22.         {
  23.             if (i == 0 || j == 0)
  24.                 LCSuff[i][j] = 0;
  25.             else if (X[i-1] == Y[j-1])
  26.             {
  27.                 LCSuff[i][j] = LCSuff[i-1][j-1] + 1;
  28.                 result = max(result, LCSuff[i][j]);
  29.             }
  30.             else LCSuff[i][j] = 0;
  31.         }
  32.     }
  33.     return result;
  34. }
  35.  
  36. /*Main */
  37. int main()
  38. {
  39.     char X[] = "Sanfoundry";
  40.     char Y[] = "foundation";
  41.     int m = strlen(X);
  42.     int n = strlen(Y);
  43.     cout << "Length of Longest Common Substring is " << LCSubStr(X, Y, m, n);
  44.     return 0;
  45. }

$ g++ lcs.cpp
$ a.out
 
Length of Longest Common Substring is 5
 
------------------
(program exited with code: 1)
Press return to continue

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.