-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0005-longest-palindromic-substring.js
More file actions
50 lines (40 loc) · 1.27 KB
/
0005-longest-palindromic-substring.js
File metadata and controls
50 lines (40 loc) · 1.27 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
42
43
44
45
46
47
48
49
50
/**
* Expand Around Center
* Time O(N^2) | Space O(1)
* https://leetcode.com/problems/longest-palindromic-substring/
* @param {string} s
* @return {string}
*/
var longestPalindrome = (s) => {
const isEmpty = s.length === 0;
if (isEmpty) return '';
const [left, right] = search(s); /* Time O(N * N) */
return s.slice(
left,
right + 1,
); /* Time O(N * N) | Ignore Auxillary Space (N) */
};
const search = (s, left = 0, right = 0) => {
for (let index = 0; index < s.length; index++) {
/* Time O(N) */
const len1 = getLength(s, index, index); /* Time O(N) */
const len2 = getLength(s, index, index + 1); /* Time O(N) */
const [length, window] = [Math.max(len1, len2), right - left];
const canSkip = length <= window;
if (canSkip) continue;
left = index - ((length - 1) >> 1);
right = index + (length >> 1);
}
return [left, right];
};
const getLength = (s, left, right) => {
const canExpand = () => 0 <= left && right < s.length;
const isSame = () => s[left] === s[right];
const isPalindrome = () => canExpand() && isSame();
while (isPalindrome()) {
left--;
right++;
} /* Time O(N) */
const window = right - left - 1;
return window;
};