-
Notifications
You must be signed in to change notification settings - Fork 40
/
LongestPalindromicSubstring.js
59 lines (49 loc) · 1.68 KB
/
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Source : https://oj.leetcode.com/problems/longest-palindromic-substring/
// Author : Dean Shi
// Date : 2015-06-02
/**********************************************************************************
*
* Given a string S, find the longest palindromic substring in S.
* You may assume that the maximum length of S is 1000,
* and there exists one unique longest palindromic substring.
*
**********************************************************************************/
/**
* @param {string} s
* @return {string}
*/
// The following code should be optimized.
var longestPalindrome = function(s) {
var tmp, index, max = '';
for (var i = 1, l = s.length; i < l; ++i) {
if (s[i + 1] === s[i - 1]) {
tmp = s[i - 1] + s[i] + s[i + 1];
index = 2;
while ((i - index >= 0) && (i + index < l)) {
if (s[i - index] === s[i + index]) {
tmp = s[i - index] + tmp + s[i + index];
} else {
break;
}
++index;
}
(max.length < tmp.length) && (max = tmp);
}
if (s[i] === s[i - 1]) {
tmp = s[i - 1] + s[i];
index = 2;
while ((i - index >= 0) && ((i + index - 1) < l)) {
if (s[i - index] === s[i + index - 1]) {
tmp = s[i - index] + tmp + s[i + index - 1];
} else {
break;
}
++index;
}
(max.length < tmp.length) && (max = tmp);
}
}
return max || s;
};
var testCase = 'abcbadddd';
console.log(longestPalindrome(testCase) === 'abcba'); // true