LeetCode 0214. Shortest Palindrome Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0214. Shortest Palindrome

Description

You are given a string s. You can convert s to a palindrome by adding characters in front of it.

Return the shortest palindrome you can find by performing this transformation.

 

Example 1:

Input: s = "aacecaaa"
Output: "aaacecaaa"

Example 2:

Input: s = "abcd"
Output: "dcbabcd"

 

Constraints:

  • 0 <= s.length <= 5 * 104
  • s consists of lowercase English letters only.

Solutions

Solution 1

PythonJavaC++GoRustC#
class Solution: def shortestPalindrome(self, s: str) -> str: base = 131 mod = 10**9 + 7 n = len(s) prefix = suffix = 0 mul = 1 idx = 0 for i, c in enumerate(s): prefix = (prefix * base + (ord(c) - ord('a') + 1)) % mod suffix = (suffix + (ord(c) - ord('a') + 1) * mul) % mod mul = (mul * base) % mod if prefix == suffix: idx = i + 1 return s if idx == n else s[idx:][::-1] + s(code-box)

Solution 2: KMP Algorithm

According to the problem description, we need to reverse the string s to obtain the string rev, and then find the longest common part of the suffix of the string rev and the prefix of the string s. We can use the KMP algorithm to concatenate the string s and the string rev and find the longest common part of the longest prefix and the longest suffix.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the string s.

PythonJavaC++GoTypeScriptC#
class Solution: def shortestPalindrome(self, s: str) -> str: t = s + "#" + s[::-1] + "$" n = len(t) next = [0] * n next[0] = -1 i, j = 2, 0 while i < n: if t[i - 1] == t[j]: j += 1 next[i] = j i += 1 elif j: j = next[j] else: next[i] = 0 i += 1 return s[::-1][: -next[-1]] + s(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !