Skip to content

Commit a567585

Browse files
committed
Optimized the code
1 parent b8a5193 commit a567585

File tree

1 file changed

+18
-13
lines changed

1 file changed

+18
-13
lines changed
Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,36 @@
11
/*
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.
44
* For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”
55
*/
66

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+
}
911
else {
10-
if (dp[x][y] != 0) return dp[x][y];
12+
if (dp[x][y] !== 0){
13+
return dp[x][y]
14+
}
1115
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]
1419
}
1520
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]
1723
}
1824
}
1925
}
20-
2126
}
2227

23-
function main() {
24-
const str1 = "ABCDGH"
25-
const str2 = "AEDFHR"
28+
function main () {
29+
const str1 = 'ABCDGH'
30+
const str2 = 'AEDFHR'
2631
const dp = new Array(str1.length + 1).fill(0).map(x => new Array(str2.length + 1).fill(0))
2732
const res = longestCommonSubsequence(str1.length - 1, str2.length - 1, str1, str2, dp)
28-
console.log(res);
33+
console.log(res)
2934
}
3035

3136
main()

0 commit comments

Comments
 (0)