-
Notifications
You must be signed in to change notification settings - Fork 0
/
5-longestPalindromicSubstring.js
41 lines (36 loc) · 1.94 KB
/
5-longestPalindromicSubstring.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
var longestPalindrome = function (s) {
let isPalindrome = function (s) {
for (let i = 0; i < Math.ceil(s.length / 2); i++) {
if (s[i] !== s[s.length - 1 - i]) {
return false;
}
}
return true;
};
let testSubstring = function (s, maxLength) {
for (let j = s.length - 1; j >= 0; j--) {
if (j + 1 < maxLength) {
return "";
}
if (s[0] === s[j]) {
const substring = s.slice(0, j + 1);
if (isPalindrome(substring)) {
return substring;
}
}
}
};
var result = "";
for (let i = 0; i < s.length; i++) {
const palindrome = testSubstring(s.slice(i, s.length), result.length);
if (palindrome.length > result.length) {
result = palindrome;
}
}
return result;
};
console.log(
longestPalindrome(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabcaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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