This is a C++ Program that Solves Longest Common Substring Problem using Dynamic Programming technique.
Given two strings, find the length of the longest common substring of both the given strings.
Note that this problem is different from longest common subsequence (LCS) problem.
This problem can be solved by using bottom up DP. Create a marix to store results of overlapping subproblems and start filling the matrix row wise. Check whether the current character of str1 matches with the current character of the str2.
str1 - PABCD str2 - MNABCPA length of longest common substring - 3 for substring ABC
Here is source code of the C++ Program to Solve Longest Common Substring Problem. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
using namespace std;
int longestCommonSubstring(string str1, string str2)
//matrix to store results of subproblems
//length of common substring is zero if either one of the substring is empty
//if characters match
string str1, str2;
cout<<"Enter string 1 - ";
cout<<"Enter string 2 - ";
cout<<"Length of the longest common substring is ";
In the main function, we will take input for str1 and str2. We will pass these to the function longestCommonSubstring as parameters. This function will calculate the result using bottom up DP and return the value which is displayed on the standard output.
Case-1: $ g++ longest_common_substring.cpp $ ./a.out Enter string 1 - PABCD Enter string 2 - MNABCPA Length of the longest common substring is 3
Sanfoundry Global Education & Learning Series – Dynamic Programming Problems.
To practice all Dynamic Programming Problems, here is complete set of 100+ Problems and Solutions.