-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathlongest_palindromic_substring.js
More file actions
67 lines (65 loc) · 2.1 KB
/
longest_palindromic_substring.js
File metadata and controls
67 lines (65 loc) · 2.1 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
62
63
64
65
66
67
var longestPalindrome = function (s) {
// Update the string to put hash "#" at the beginning, end and in between each character
let updatedString = getUpdatedString(s);
// Length of the array that will store the window of palindromic substring
const length = 2 * s.length + 1;
// Array to store the length of each palindrome centered at each element
let p = new Array(length);
p.fill(0);
// Current center of the longest palindromic string
let c = 0;
// Right boundary of the longest palindromic string
let r = 0;
// Maximum length of the substring
let maxLength = 0;
// Position index
let position = -1;
for (let i = 0; i < length; i++) {
// Mirror of the current index
let mirror = 2 * c - i;
// Check if the mirror is outside the left boundary of current longest palindrome
if (i < r) {
p[i] = Math.min(r - i, p[mirror]);
}
// Indices of the characters to be compared
let a = i + (1 + p[i]);
let b = i - (1 + p[i]);
// Expand the window
while (a < length && b >= 0 && updatedString[a] === updatedString[b]) {
p[i]++;
a++;
b--;
}
// If the expanded palindrome is expanding beyond the right boundary of
// the current longest palindrome, then update c and r
if (i + p[i] > r) {
c = i;
r = i + p[i];
}
if (maxLength < p[i]) {
maxLength = p[i];
position = i;
}
}
let offset = p[position];
let result = "";
for (let i = position - offset + 1; i <= position + offset - 1; i++) {
if (updatedString[i] !== '#') {
result += updatedString[i];
}
}
return result;
};
function getUpdatedString(s) {
let sb = "";
for (let i = 0; i < s.length; i++) {
sb += "#" + s[i];
}
sb += "#";
return sb;
}
console.log(longestPalindrome("babad"));
console.log(longestPalindrome("cbbd"));
console.log(longestPalindrome("a"));
console.log(longestPalindrome("ac"));
console.log(longestPalindrome("abb"));