We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent c1dd84a commit 22605baCopy full SHA for 22605ba
214-shortest-palindrome.js
@@ -50,3 +50,37 @@ function getFail(s) {
50
return table
51
}
52
53
+// another
54
+
55
+/**
56
+ * @param {string} s
57
+ * @return {string}
58
+ */
59
+const shortestPalindrome = function(s) {
60
+ const tmp = `${s}#${reverse(s)}`
61
+ const table = kmp(tmp)
62
+ return `${reverse(s.slice(table[table.length - 1]))}${s}`
63
+};
64
+function reverse(str) {
65
+ return [...str].reverse().join('')
66
+}
67
68
+function kmp(s) {
69
+ const n = s.length, table = Array(n).fill(0)
70
+ let idx = 0
71
+ for(let i = 1; i < n; ) {
72
+ if(s[i] === s[idx]) {
73
+ idx++
74
+ table[i] = idx
75
+ i++
76
+ } else {
77
+ if(idx > 0) {
78
+ idx = table[idx - 1]
79
80
+ idx = 0
81
82
+ }
83
84
85
+ return table
86
0 commit comments