-
Notifications
You must be signed in to change notification settings - Fork 154
/
longest-palindromic-subsequence.js
82 lines (71 loc) · 1.48 KB
/
longest-palindromic-subsequence.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* Longest Palindromic Subsequence
*
* Given a string s, find the longest palindromic subsequence's length in s.
* You may assume that the maximum length of s is 1000.
*
* Example 1:
* Input:
*
* "bbbab"
* Output:
* 4
* One possible longest palindromic subsequence is "bbbb".
* Example 2:
* Input:
*
* "cbbd"
* Output:
* 2
* One possible longest palindromic subsequence is "bb".
*/
/**
* Recursion
*
* @param {string} s
* @return {number}
*/
const longestPalindromeSubseqR = s => {
return helper(s, 0, s.length - 1);
};
const helper = (s, l, h) => {
if (l === h) {
return 1;
}
if (s[l] === s[h] && l + 1 === h) {
return 2;
}
if (s[l] === s[h]) {
return 2 + helper(s, l + 1, h - 1);
}
return Math.max(helper(s, l, h - 1), helper(s, l + 1, h));
};
/**
* Dynamic Programming
*
* @param {string} s
* @return {number}
*/
const longestPalindromeSubseq = s => {
const n = s.length;
const table = Array(n)
.fill()
.map(() => Array(n));
for (let i = 0; i < n; i++) {
table[i][i] = 1;
}
for (let len = 2; len <= n; len++) {
for (let i = 0; i < n - k + 1; i++) {
const j = i + len - 1;
if (s[i] === s[j] && len === 2) {
table[i][j] = 2;
} else if (s[i] === s[j]) {
table[i][j] = 2 + table[i + 1][j - 1];
} else {
table[i][j] = Math.max(table[i + 1][j], table[i][j - 1]);
}
}
}
return table[0][n - 1];
};
export { longestPalindromeSubseqR, longestPalindromeSubseq };