-
Notifications
You must be signed in to change notification settings - Fork 4
/
shortest-palindrome.js
55 lines (49 loc) · 1.04 KB
/
shortest-palindrome.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
var DEBUG = process.env.DEBUG;
/**
* @param {string} s
* @return {string}
*/
function getl(s) {
var l = [];
l.push(0);
for (var i = 1; i <= s.length; i++) {
l.push(0);
var j = i - 1;
while (j) {
j = l[j];
if (s[j] === s[i-1]) {
l[i] = j + 1;
break;
}
}
}
return l;
}
String.prototype.reverse = function () {
return this.split('').reverse().join('');
};
var shortestPalindrome = function(s) {
var l = getl(s);
var rs = s.reverse();
var i = 0, matchedL = 0;
while (true) {
if (i === rs.length)
break;
if (rs[i] === s[matchedL]) {
i++;
matchedL++;
} else {
if (matchedL === 0) i++;
else matchedL = l[matchedL];
}
}
return s.substring(matchedL).reverse() + s;
};
function test(f) {
[
[[]]
].forEach(function (input) {
console.log(f.apply(undefined, input));
});
}
if (DEBUG) test();