Skip to content

Commit

Permalink
Add Itrative version of Longest Common Subsequence
Browse files Browse the repository at this point in the history
  • Loading branch information
miladra committed Jul 6, 2022
1 parent 7252a1b commit bbf6afa
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions java/1143-Longest-Common-Subsequence.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,39 @@ public int LCS(String s1, String s2, int i, int j, int[][] dp) {
}

}


// Itrative 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;
}

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];

} else {
dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
}

}
}

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

0 comments on commit bbf6afa

Please sign in to comment.