Skip to content

Commit

Permalink
Create 1143-Longest-Common-Subsequence.java
Browse files Browse the repository at this point in the history
  • Loading branch information
SharmaTushar1 authored Jul 6, 2022
1 parent a758e1d commit fec58bd
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions java/1143-Longest-Common-Subsequence.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//memoized version

class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int[][] dp = new int[text1.length()][text2.length()];
return LCS(text1, text2, 0, 0, dp);
}

public int LCS(String s1, String s2, int i, int j, int[][] dp) {
if (i>=s1.length() || j>=s2.length()) return 0;
else if (dp[i][j]!=0) return dp[i][j];
else if (s1.charAt(i) == s2.charAt(j)) return 1+LCS(s1, s2, i+1, j+1, dp);
else{
dp[i][j] = Math.max(LCS(s1, s2, i+1, j, dp), LCS(s1, s2, i, j+1, dp));
return dp[i][j];
}
}

}

0 comments on commit fec58bd

Please sign in to comment.