Palindrome Completion
Completing a string to a palindrome with the minimal number of characters.
For the leetcode daily ‘shortest palindrome’ question.
Analysis
It is relatively easy to find a trivial solution - first, check is the entire string is a palindrome, then the n-1
substring, and so on. Whenever a palindrome is found, reverse the remainder of the string and throw it in front.
Solutions
The Trivial Solution
# start snippet solution_trivial
class SolutionTrivial:
def shortestPalindrome(self, s: str):
= len(s)
n if n <= 1:
return s
= 0
best_init for k in range(n, 0, -1):
if (t := s[0:k]) == t[::-1]:
= k
best_init break
= s[best_init:]
mantisa return mantisa[::-1] + s
# stop snippet trivial