1143. Longest Common Subsequence
//if last character at the last index is different
if (text1[i-1]!=text2[j-1]){
dp[i][j]=max(dp[i-1][j], dp[i][j-1]);
}
// if the last character is the same
if (text1[i-1]!=text2[j-1]){
dp[i][j]=dp[i-1][j-1]+1, dp[i][j-1];
}class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int[][] memo = new int[text1.length()+1][text2.length()+1];
for( int i =1;i<memo.length; i++){
for(int j=1; j<memo[0].length; j++){
if(text1.charAt(i-1)==text2.charAt(j-1))
memo[i][j]=memo[i-1][j-1]+1;
else
memo[i][j]=Math.max(memo[i-1][j],memo[i][j-1]);
}
}
return memo[text1.length()][text2.length()];
}
}Last updated