Here is the question statement
Given two strings s1 and s2, return the length of their longest common subsequence.
A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings.
If there is no common subsequence, return 0.
Here is my code
class Solution {
public:
int dp[1001][1001];
int lcs(string s1,string s2,int n,int m){
if (n==0 || m == 0)
return 0;
if(dp[n][m]!=-1)
return dp[n][m];
if (s1[n-1] == s2[m-1])
{
return dp[n][m]= 1 + lcs(s1,s2,n-1,m-1);
}
else
{
return dp[n][m]= max(lcs(s1,s2,n-1,m), lcs(s1,s2,n,m-1));
}
return dp[n][m];
}
int longestCommonSubsequence(string s1, string s2) {
memset(dp,-1,1001*1001*sizeof(int));
return lcs(s1,s2, s1.size(), s2.size());
}
};
Thank You
use call by reference in function definition instead of call by value.
int lcs(string &s1,string &s2,int n,int m);
int longestCommonSubsequence(string &s1, string &s2);