-
-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathlongestPalindromicSubstring.js
More file actions
61 lines (55 loc) · 1.53 KB
/
longestPalindromicSubstring.js
File metadata and controls
61 lines (55 loc) · 1.53 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
51
52
53
54
55
56
57
58
59
60
61
/**
* Finds the longest palindromic substring in a given string using expand-around-center.
* @param {string} str
* @returns {string}
*/
function longestPalindromicSubstring(str) {
if (!str || str.length <= 1) return str;
let left = 0,
right = 0;
for (let i = 0; i < str.length; i++) {
// Odd length palindrome
let [left1, right1] = expandAroundCenter(str, i, i);
// Even length palindrome
let [left2, right2] = expandAroundCenter(str, i, i + 1);
if (right1 - left1 > right - left) {
left = left1;
right = right1;
}
if (right2 - left2 > right - left) {
left = left2;
right = right2;
}
}
return str.substring(left, right + 1);
}
/**
* Expands around the given center and returns the bounds of the palindrome.
* @param {string} str
* @param {number} left
* @param {number} right
* @returns {[number, number]}
*/
function expandAroundCenter(str, left, right) {
while (left >= 0 && right < str.length && str[left] === str[right]) {
left--;
right++;
}
return [left + 1, right - 1];
}
// Test cases
const testCases = [
{ str: "ababd", expected: "aba" },
{ str: "dbbc", expected: "bb" },
{ str: "babad", expected: "bab" }, // or "aba"
{ str: "cbbd", expected: "bb" },
{ str: "a", expected: "a" },
{ str: "ac", expected: "a" }, // or "c"
{ str: "", expected: "" },
];
for (const { str, expected } of testCases) {
const result = longestPalindromicSubstring(str);
console.log(
`Input: "${str}" | Output: "${result}" | Expected: "${expected}"`
);
}