Skip to content

Commit 5895707

Browse files
Merge pull request #2652 from ColstonBod-oy/patch-11
Update 1143-longest-common-subsequence.java
2 parents 299448e + e8cc89c commit 5895707

File tree

1 file changed

+8
-21
lines changed

1 file changed

+8
-21
lines changed

Diff for: java/1143-longest-common-subsequence.java

+8-21
Original file line numberDiff line numberDiff line change
@@ -22,33 +22,20 @@ public int LCS(String s1, String s2, int i, int j, int[][] dp) {
2222

2323
// Iterative version
2424
class Solution {
25-
25+
2626
public int longestCommonSubsequence(String text1, String text2) {
27-
//O(n*m)/O(n*m) time/memory
28-
if (text1.isEmpty() || text2.isEmpty()) {
29-
return 0;
30-
}
31-
32-
int[][] dp = new int[text1.length() + 1][text2.length() + 1];
33-
34-
for (int i = 0; i <= text1.length(); i++) {
35-
dp[i][0] = 0;
36-
}
37-
38-
for (int j = 0; j <= text2.length(); j++) {
39-
dp[0][j] = 0;
40-
}
27+
int[][] dp = new int[text1.length() + 1][text2.length() + 1];
4128

42-
for (int i = 1; i <= text1.length(); i++) {
43-
for (int j = 1; j <= text2.length(); j++) {
44-
if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
45-
dp[i][j] = 1 + dp[i - 1][j - 1];
29+
for (int i = text1.length() - 1; i >= 0; i--) {
30+
for (int j = text2.length() - 1; j >= 0; j--) {
31+
if (text1.charAt(i) == text2.charAt(j)) {
32+
dp[i][j] = 1 + dp[i + 1][j + 1];
4633
} else {
47-
dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
34+
dp[i][j] = Math.max(dp[i][j + 1], dp[i + 1][j]);
4835
}
4936
}
5037
}
5138

52-
return dp[text1.length()][text2.length()];
39+
return dp[0][0];
5340
}
5441
}

0 commit comments

Comments
 (0)