-
Notifications
You must be signed in to change notification settings - Fork 0
/
PalindromicSubstring.js
48 lines (39 loc) · 1.12 KB
/
PalindromicSubstring.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
/* description :
Given a string s, return the longest
palindromic substring in s.
Example 1:
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb" */
/* ---------------------------------------------------------- */
var longestPalindrome = (s) => {
let longest = '';
for (let i = 0; i < s.length; i++) {
// Check odd-length palindromes
let left = i, right = i;
while (left >= 0 && right < s.length && s[left] === s[right]) {
let palindrome = s.substring(left, right + 1);
if (palindrome.length > longest.length) {
longest = palindrome;
}
left--;
right++;
}
// Check even-length palindromes
left = i;
right = i + 1;
while (left >= 0 && right < s.length && s[left] === s[right]) {
let palindrome = s.substring(left, right + 1);
if (palindrome.length > longest.length) {
longest = palindrome;
}
left--;
right++;
}
}
return longest;
};
console.log(longestPalindrome('cbbd'))