Skip to content

Commit 942d294

Browse files
committedNov 24, 2019
提交214 最短回文串
1 parent 2030cd9 commit 942d294

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
 

‎214.最短回文串/solution.html

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6+
<meta http-equiv="X-UA-Compatible" content="ie=edge">
7+
<title>Document</title>
8+
</head>
9+
<body>
10+
<script>
11+
// Source : https://leetcode.com/problems/shortest-palindrome/
12+
// Author : 悬笔e绝
13+
// Date : 2019-11-24
14+
15+
/**
16+
* @param {string} s
17+
* @return {string}
18+
*/
19+
20+
function Manacher(s) {
21+
var str = '*#'
22+
, dp = []
23+
, maxn = 0
24+
, idx = 0;
25+
26+
for (var i = 0, len = s.length; i < len; i++)
27+
str += s[i] + '#';
28+
29+
for (var i = 1, len = str.length; i < len; i++) {
30+
if (maxn > i) dp[i] = Math.min(dp[2 * idx - i], maxn - i);
31+
else dp[i] = 1;
32+
33+
while (str[i - dp[i]] === str[i + dp[i]]) dp[i]++;
34+
35+
if (dp[i] + i > maxn)
36+
maxn = dp[i] + i, idx = i;
37+
}
38+
39+
var ans = 0
40+
, pos;
41+
42+
var pos;
43+
for (var i = 1; i < len; i++) {
44+
if (i === dp[i])
45+
pos = i;
46+
}
47+
48+
var tmp = str[pos] === '#' ? '' : str[pos];
49+
for (var i = pos + 1; i < len; i++) {
50+
var res = str[i] === '#' ? '' : str[i];
51+
tmp = res + tmp + res;
52+
}
53+
54+
return tmp;
55+
}
56+
57+
var shortestPalindrome = function(s) {
58+
var str = Manacher(s);
59+
return str;
60+
};
61+
62+
//测试
63+
var s = "aacecaaa";
64+
console.log('shortestPalindrome', shortestPalindrome(s));
65+
</script>
66+
</body>
67+
</html>

0 commit comments

Comments
 (0)
Please sign in to comment.