|
1 | 1 | /* |
2 | | - * Given two sequences, find the length of longest subsequence present in both of them. |
3 | | - * A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. |
| 2 | + * Given two sequences, find the length of longest subsequence present in both of them. |
| 3 | + * A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. |
4 | 4 | * For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg” |
5 | 5 | */ |
6 | 6 |
|
7 | | -function longestCommonSubsequence(x, y, str1, str2, dp) { |
8 | | - if (x == -1 || y == -1) return 0; |
| 7 | +function longestCommonSubsequence (x, y, str1, str2, dp) { |
| 8 | + if (x === -1 || y === -1) { |
| 9 | + return 0 |
| 10 | + } |
9 | 11 | else { |
10 | | - if (dp[x][y] != 0) return dp[x][y]; |
| 12 | + if (dp[x][y] !== 0){ |
| 13 | + return dp[x][y] |
| 14 | + } |
11 | 15 | else { |
12 | | - if (str1[x] == str2[y]) { |
13 | | - return dp[x][y] = 1 + longestCommonSubsequence(x - 1, y - 1, str1, str2, dp); |
| 16 | + if (str1[x] === str2[y]) { |
| 17 | + dp[x][y] = 1 + longestCommonSubsequence(x - 1, y - 1, str1, str2, dp); |
| 18 | + return dp[x][y] |
14 | 19 | } |
15 | 20 | else { |
16 | | - return dp[x][y] = Math.max(longestCommonSubsequence(x - 1, y, str1, str2, dp), longestCommonSubsequence(x, y - 1, str1, str2, dp)) |
| 21 | + dp[x][y] = Math.max(longestCommonSubsequence(x - 1, y, str1, str2, dp), longestCommonSubsequence(x, y - 1, str1, str2, dp)) |
| 22 | + return dp[x][y] |
17 | 23 | } |
18 | 24 | } |
19 | 25 | } |
20 | | - |
21 | 26 | } |
22 | 27 |
|
23 | | -function main() { |
24 | | - const str1 = "ABCDGH" |
25 | | - const str2 = "AEDFHR" |
| 28 | +function main () { |
| 29 | + const str1 = 'ABCDGH' |
| 30 | + const str2 = 'AEDFHR' |
26 | 31 | const dp = new Array(str1.length + 1).fill(0).map(x => new Array(str2.length + 1).fill(0)) |
27 | 32 | const res = longestCommonSubsequence(str1.length - 1, str2.length - 1, str1, str2, dp) |
28 | | - console.log(res); |
| 33 | + console.log(res) |
29 | 34 | } |
30 | 35 |
|
31 | 36 | main() |
0 commit comments