8/31/2020

[LeetCode] 214. Shortest Palindrome

Problem : https://leetcode.com/problems/shortest-palindrome/

The quiz asks to add character only in front of the original string.

That means the characters be added in front must come from the end of the string and in reversed order. 

Generally it is the form of   [R'] + [Palindrome] + [R].

R' = reversed R

Let S' = revered S, then there must be S'[i:] == S[:Len(S) - i].  The answer is adding the longest S'[0:i] in front of S


class Solution:
    def shortestPalindrome(self, s: str) -> str:
        r = s[::-1]
        
        for i in range(len(s)):
            if r[i:] == s[:len(s)-i]:
                return r[:i] + s
        
        return s

No comments:

Post a Comment