From e8cc89c5c5665e5176e6a144f915e9c05e63c638 Mon Sep 17 00:00:00 2001 From: Colston Bod-oy <75562733+ColstonBod-oy@users.noreply.github.com> Date: Tue, 27 Jun 2023 17:49:40 +0800 Subject: [PATCH] Update 1143-longest-common-subsequence.java Modified the iterative version to be bottom-up as well and removed unnecessary for loops. --- java/1143-longest-common-subsequence.java | 29 +++++++---------------- 1 file changed, 8 insertions(+), 21 deletions(-) diff --git a/java/1143-longest-common-subsequence.java b/java/1143-longest-common-subsequence.java index 59071919f..478745e8b 100644 --- a/java/1143-longest-common-subsequence.java +++ b/java/1143-longest-common-subsequence.java @@ -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]; } }