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
If you wish to look at all C++ Programming examples, go to C++ Programs.

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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 40s–60s and exploring new directions in your career, I also offer mentoring. Learn more here.