Skip to content

Commit d5080ea

Browse files
author
shangchun
committed
Longest Palindromic Substring
1 parent af790b6 commit d5080ea

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

longestPalindromicSubstring.js

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*jshint node:true, white:true*/
2+
var assert = require('assert');
3+
4+
/**
5+
* 最长回文,线性复杂度
6+
* @link http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
7+
* @method longestPalindrome
8+
* @param {String} s
9+
* @return {String}
10+
*/
11+
function longestPalindrome(s) {
12+
var T = preProcess(s),
13+
len = T.length,
14+
P = [],
15+
C = 0,
16+
R = 0,
17+
i,
18+
iMirror,
19+
maxLen = 0,
20+
centerIndex = 0;
21+
22+
for (i = 1; i < len - 1; ++i) {
23+
iMirror = 2 * C - i; // equals to i' = C - (i-C)
24+
25+
P[i] = (R > i) ? Math.min(R - i, P[iMirror]) : 0;
26+
27+
// Attempt to expand palindrome centered at i
28+
while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) {
29+
P[i]++;
30+
}
31+
32+
// If palindrome centered at i expand past R,
33+
// adjust center based on expanded palindrome.
34+
if (i + P[i] > R) {
35+
C = i;
36+
R = i + P[i];
37+
}
38+
}
39+
40+
// Find the maximum element in P.
41+
for (i = 1; i < len - 1; ++i) {
42+
if (P[i] > maxLen) {
43+
maxLen = P[i];
44+
centerIndex = i;
45+
}
46+
}
47+
48+
return s.substr((centerIndex - 1 - maxLen) / 2, maxLen);
49+
}
50+
51+
/**
52+
* Transform S into T.
53+
* For example, S = "abba", T = "^#a#b#b#a#$".
54+
* ^ and $ signs are sentinels appended to each end to avoid bounds checking
55+
* @method preProcess
56+
* @param {String} s
57+
* @return {String}
58+
*/
59+
function preProcess(s) {
60+
var len = s.length,
61+
i,
62+
ret;
63+
if (len === 0) return "^$";
64+
65+
ret = "^";
66+
for (i = 0; i < len; ++i) {
67+
ret += "#" + s.substr(i, 1);
68+
}
69+
ret += "#$";
70+
return ret;
71+
}
72+
73+
assert.equal(longestPalindrome(''), '', 'empty');
74+
assert.equal(longestPalindrome('abcd'), 'a', 'trivial solution');
75+
assert.equal(longestPalindrome('aba'), 'aba', 'full palindromic');
76+
assert.equal(longestPalindrome('abac'), 'aba', 'part palindromic');
77+
assert.equal(longestPalindrome('caba'), 'aba', 'part palindromic');
78+
assert.equal(longestPalindrome('babcbabcbaccba'), 'abcbabcba', 'part palindromic');

0 commit comments

Comments
 (0)