-
Notifications
You must be signed in to change notification settings - Fork 33
/
005-Longest-Palindromic-Substring.js
53 lines (49 loc) · 2.31 KB
/
005-Longest-Palindromic-Substring.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
49
50
51
52
53
/**
* https://leetcode.com/problems/longest-palindromic-substring/description/
* Difficulty:Medium
*
* Given a string s, find the longest palindromic substring in s.
* You may assume that the maximum length of s is 1000.
*
* Example:
* Input: "babad"
* Output: "bab"
* Note: "aba" is also a valid answer.
*
* Example:
* Input: "cbbd"
* Output: "bb"
*/
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function (s) {
var a = new Date();
var n = s.length;
var res = '';
var dp = [];
while (dp.push(new Array(n).fill(-1)) < n);
// console.log(dp);
for (var i = n - 1; i >= 0; i--) {
for (var j = i; j < n; j++) {
dp[i][j] = s[i] === s[j] && ((j - i < 3) || dp[i + 1][j - 1]);
if (dp[i][j] === undefined) {
console.log(i, j, s[i], s[j], dp[i + 1][j - 1])
}
if (dp[i][j]) {
var tmp = s.substring(i, j + 1);
if (tmp.length > res.length) res = tmp;
}
}
}
// console.log(dp);
console.log(new Date() - a);
return res;
};
// console.log(isPalindrome(s, 1, 3));
// console.log(longestPalindrome('babad'));
// console.log(longestPalindrome(''));
// console.log(longestPalindrome('a'));
// console.log(longestPalindrome('aabbbbbb'));
console.log(longestPalindrome("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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