-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlongestPalindrome.js
More file actions
30 lines (29 loc) · 795 Bytes
/
longestPalindrome.js
File metadata and controls
30 lines (29 loc) · 795 Bytes
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
var longestPalindrome = function (s) {
let subStr = '';
// inside the for loop we will check if it satisfies 2 conditions (odd or even)
for (let i = 0; i < s.length; i++) {
let left = i;
let right = i;
console.log(`initial ${left} & ${right}`);
// odd length
while (left >= 0 && right < s.length && s[left] === s[right]) {
if (right - left + 1 > subStr.length) {
subStr = s.substring(left, right + 1);
console.log(subStr);
}
left--;
right++;
}
// even length
left = i;
right = i + 1;
while (left >= 0 && right < s.length && s[left] === s[right]) {
if (right - left + 1 > subStr.length) {
subStr = s.substring(left, right + 1);
}
left--;
right++;
}
}
return subStr;
};