|
| 1 | +/** |
| 2 | + input : string text1, text2 |
| 3 | + output : length of lcs else 0 |
| 4 | + constraints: |
| 5 | + 1) both input strings are not empty |
| 6 | + 2) input strings are consist of lowercase eng. letters |
| 7 | +
|
| 8 | + solution 1) brute force |
| 9 | +
|
| 10 | + nested for loop |
| 11 | + tc : O(n^2 * m) where n is min (len(text1), len(text2)), m is max |
| 12 | + sc : O(1) |
| 13 | +
|
| 14 | + solution 2) dp |
| 15 | +
|
| 16 | + at each step we have 3 conditions |
| 17 | +
|
| 18 | + 1. current characters are same. compare next characters |
| 19 | + abcde. ith index |
| 20 | + ^ |
| 21 | + abc. jth index |
| 22 | + ^ |
| 23 | + then go to next and maximum length also increases |
| 24 | + move (i + 1, j+1) |
| 25 | + 2, 3. current characters are different. move i or j to compare |
| 26 | +
|
| 27 | + abcde |
| 28 | + ^ |
| 29 | + abc |
| 30 | + ^ |
| 31 | + move (i +1, j) or (i, j+1) |
| 32 | +
|
| 33 | +
|
| 34 | + let dp[i][j] max length of lcs |
| 35 | +
|
| 36 | + a b c d e |
| 37 | + a 1 1 1 1 1 |
| 38 | + c 1 1 2 2 2 |
| 39 | + e 1 1 2 2 3 |
| 40 | +
|
| 41 | + a b d e f g h |
| 42 | + a 1 1 1 1 1 1 1 |
| 43 | + f 1 1 1 1 2 2 2 |
| 44 | + h 1 1 1 1 2 2 3 |
| 45 | + d 1 1 2 2 2 2 3 |
| 46 | +
|
| 47 | + if equals |
| 48 | + dp[i][j] = dp[i-1][j-1] + 1 |
| 49 | + else |
| 50 | + dp[i][j] = max(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) |
| 51 | + tc : O(mn) |
| 52 | + sc : O(mn) > O(min(m, n)) if optimize space to 2-Row array |
| 53 | + */ |
| 54 | +class Solution { |
| 55 | + public int longestCommonSubsequence(String text1, String text2) { |
| 56 | + int m = text1.length(), n = text2.length(); |
| 57 | + if(m < n) { |
| 58 | + return longestCommonSubsequence(text2, text1); |
| 59 | + } |
| 60 | + int[][] dp = new int[2][n+1]; |
| 61 | + int prevRow = 0; |
| 62 | + int curRow = 1; |
| 63 | + for(int i = 1; i <= m; i++) { |
| 64 | + for(int j = 1; j <= n; j++) { |
| 65 | + if(text1.charAt(i-1) == text2.charAt(j-1)) { |
| 66 | + dp[curRow][j] = dp[prevRow][j-1] + 1; |
| 67 | + } else { |
| 68 | + dp[curRow][j] = Math.max(dp[prevRow][j], dp[curRow][j-1]); |
| 69 | + } |
| 70 | + } |
| 71 | + curRow = prevRow; |
| 72 | + prevRow = (prevRow + 1) % 2; |
| 73 | + } |
| 74 | + return dp[prevRow][n]; |
| 75 | + } |
| 76 | +} |
0 commit comments