-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathlongest-palindromic-substring.js
85 lines (72 loc) · 1.52 KB
/
longest-palindromic-substring.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
83
84
85
/**
* Longest Palindromic Substring
*
* Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
*
* Example:
*
* Input: "babad"
*
* Output: "bab"
*
* Note: "aba" is also a valid answer.
* Example:
*
* Input: "cbbd"
*
* Output: "bb"
*
*/
/**
* Solution 1: Dynamic Programming
*
* @param {string} s
* @return {string}
*/
const longestPalindrome = s => {
const n = s.length;
const dp = [];
for (let i = 0; i < n; i++) {
dp[i] = [];
}
let result = '';
for (let i = n - 1; i >= 0; i--) {
for (let j = i; j < n; j++) {
dp[i][j] = s[i] === s[j] && (j - i <= 2 || dp[i + 1][j - 1]);
if (dp[i][j] && j - i + 1 > result.length) {
result = s.substring(i, j + 1);
}
}
}
return result;
};
/**
* Solution 2: Expand Around Center
*
* @param {string} s
* @return {string}
*/
const longestPalindromeExpand = s => {
let start = 0;
let end = 0;
for (let i = 0; i < s.length; i++) {
const len1 = expandAroundCenter(s, i, i);
const len2 = expandAroundCenter(s, i, i + 1);
const len = Math.max(len1, len2);
if (len > end - start) {
start = i - Math.floor((len - 1) / 2);
end = i + Math.floor(len / 2);
}
}
return s.substring(start, end + 1);
};
const expandAroundCenter = (s, left, right) => {
let L = left;
let R = right;
while (L >= 0 && R < s.length && s[L] === s[R]) {
L--;
R++;
}
return R - L - 1;
};
export { longestPalindrome, longestPalindromeExpand };