Skip to content

Commit fec58bd

Browse files
Create 1143-Longest-Common-Subsequence.java
1 parent a758e1d commit fec58bd

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
//memoized version
2+
3+
class Solution {
4+
public int longestCommonSubsequence(String text1, String text2) {
5+
int[][] dp = new int[text1.length()][text2.length()];
6+
return LCS(text1, text2, 0, 0, dp);
7+
}
8+
9+
public int LCS(String s1, String s2, int i, int j, int[][] dp) {
10+
if (i>=s1.length() || j>=s2.length()) return 0;
11+
else if (dp[i][j]!=0) return dp[i][j];
12+
else if (s1.charAt(i) == s2.charAt(j)) return 1+LCS(s1, s2, i+1, j+1, dp);
13+
else{
14+
dp[i][j] = Math.max(LCS(s1, s2, i+1, j, dp), LCS(s1, s2, i, j+1, dp));
15+
return dp[i][j];
16+
}
17+
}
18+
19+
}

0 commit comments

Comments
 (0)