Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2652 from ColstonBod-oy/patch-11
Browse files Browse the repository at this point in the history
Update 1143-longest-common-subsequence.java
  • Loading branch information
sujal-goswami authored Aug 10, 2023
2 parents 299448e + e8cc89c commit 5895707
Showing 1 changed file with 8 additions and 21 deletions.
29 changes: 8 additions & 21 deletions java/1143-longest-common-subsequence.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,33 +22,20 @@ public int LCS(String s1, String s2, int i, int j, int[][] dp) {

// Iterative version
class Solution {

public int longestCommonSubsequence(String text1, String text2) {
//O(n*m)/O(n*m) time/memory
if (text1.isEmpty() || text2.isEmpty()) {
return 0;
}

int[][] dp = new int[text1.length() + 1][text2.length() + 1];

for (int i = 0; i <= text1.length(); i++) {
dp[i][0] = 0;
}

for (int j = 0; j <= text2.length(); j++) {
dp[0][j] = 0;
}
int[][] dp = new int[text1.length() + 1][text2.length() + 1];

for (int i = 1; i <= text1.length(); i++) {
for (int j = 1; j <= text2.length(); j++) {
if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
dp[i][j] = 1 + dp[i - 1][j - 1];
for (int i = text1.length() - 1; i >= 0; i--) {
for (int j = text2.length() - 1; j >= 0; j--) {
if (text1.charAt(i) == text2.charAt(j)) {
dp[i][j] = 1 + dp[i + 1][j + 1];
} else {
dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
dp[i][j] = Math.max(dp[i][j + 1], dp[i + 1][j]);
}
}
}

return dp[text1.length()][text2.length()];
return dp[0][0];
}
}

0 comments on commit 5895707

Please sign in to comment.