-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0516-longest-palindromic-subsequence.js
More file actions
41 lines (37 loc) · 1.09 KB
/
0516-longest-palindromic-subsequence.js
File metadata and controls
41 lines (37 loc) · 1.09 KB
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
/**
* Longest Palindromic Subsequence
* Time Complexity: O(N^2)
* Space Complexity: O(N^2)
*/
var longestPalindromeSubseq = function (s) {
const inputStringLength = s.length;
if (inputStringLength === 0) {
return 0;
}
const dpResultMatrix = Array(inputStringLength)
.fill(null)
.map(() => Array(inputStringLength).fill(0));
for (
let outerLoopIndex = inputStringLength - 1;
outerLoopIndex >= 0;
outerLoopIndex--
) {
dpResultMatrix[outerLoopIndex][outerLoopIndex] = 1;
for (
let innerLoopIndex = outerLoopIndex + 1;
innerLoopIndex < inputStringLength;
innerLoopIndex++
) {
if (s[outerLoopIndex] === s[innerLoopIndex]) {
dpResultMatrix[outerLoopIndex][innerLoopIndex] =
2 + dpResultMatrix[outerLoopIndex + 1][innerLoopIndex - 1];
} else {
dpResultMatrix[outerLoopIndex][innerLoopIndex] = Math.max(
dpResultMatrix[outerLoopIndex + 1][innerLoopIndex],
dpResultMatrix[outerLoopIndex][innerLoopIndex - 1],
);
}
}
}
return dpResultMatrix[0][inputStringLength - 1];
};