C++ Program to Find 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. }

advertisement
$ 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
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn