Longest Palindromic Substring LeetCode solution in JavaScript

1
/*
2
* @param {string} s
3
* @return {string}
4
*/
5
var longestPalindrome = function (s) {
6
let longestP = s[0];
7
let palindrome = "";
8
if (s.length === 1) return s;
9

10
//the length of the palindrome is odd
11
for (let index = 1; index < s.length - 1; index++) {
12
if (s[index - 1] === s[index + 1]) {
13
palindrome = s[index - 1] + s[index] + s[index + 1];
14
for (let k = 1; index - 1 - k > -1 && index + 1 + k < s.length; k++) {
15
if (s[index - 1 - k] === s[index + 1 + k]) {
16
palindrome = s[index - 1 - k] + palindrome + s[index + 1 + k];
17
} else {
18
break;
19
}
20
}
21
}
22
if (palindrome.length > longestP.length) {
23
longestP = palindrome;
24
}
25
palindrome = "";
26
}
27

28
//the length of the palindrome is pair
29
for (let index = 0; index < s.length - 1; index++) {
30
if (s[index] === s[index + 1]) {
31
palindrome = s[index] + s[index + 1];
32
for (let k = 1; index - k > -1 && index + 1 + k < s.length; k++) {
33
if (s[index - k] === s[index + 1 + k]) {
34
palindrome = s[index - k] + palindrome + s[index + 1 + k];
35
} else {
36
break;
37
}
38
}
39
}
40
if (palindrome.length > longestP.length) {
41
longestP = palindrome;
42
}
43
palindrome = "";
44
}
45
return longestP;
46
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0