-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0214-shortest-palindrome.py
More file actions
39 lines (36 loc) · 1.33 KB
/
0214-shortest-palindrome.py
File metadata and controls
39 lines (36 loc) · 1.33 KB
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
# time complexity: O(n)
# space complexity: O(n)
class Solution:
def shortestPalindrome(self, s: str) -> str:
if not s:
return s
modifiedString = self.preprocessString(s)
n = len(modifiedString)
palindromeRadiusArray = [0] * n
center = 0
rightBoundary = 0
maxPalindromeLength = 0
for i in range(1, n - 1):
mirrorIndex = 2 * center - i
if rightBoundary > i:
palindromeRadiusArray[i] = min(
rightBoundary - i, palindromeRadiusArray[mirrorIndex]
)
while (
modifiedString[i + 1 + palindromeRadiusArray[i]]
== modifiedString[i - 1 - palindromeRadiusArray[i]]
):
palindromeRadiusArray[i] += 1
if i + palindromeRadiusArray[i] > rightBoundary:
center = i
rightBoundary = i + palindromeRadiusArray[i]
if i - palindromeRadiusArray[i] == 1:
maxPalindromeLength = max(
maxPalindromeLength, palindromeRadiusArray[i]
)
suffix = s[maxPalindromeLength:][::-1]
return suffix + s
def preprocessString(self, s: str) -> str:
return "^" + "#" + "#".join(s) + "#$"
s = "abcd"
print(Solution().shortestPalindrome(s))