My AC python solution for your reference.


  • 0
    L

    compare with left part and right part, if same, then we can add the left part to string.

    class Solution:
    # @param {string} s
    # @return {string}
    def shortestPalindrome(self, s):
    	r=s[::-1];
    
    	left=s[1:][::-1];
    	middle= len(s)//2+1;
    	while(middle>=0):
    		if(r[len(s)-middle:]==s[middle+1:middle+1+middle]):
    			left=s[middle+1+middle:][::-1];
    			break;
    		if(r[len(s)-middle:]==s[middle:middle+middle]):
    			left=s[middle+middle:][::-1];
    			break;
    		middle-=1;
    
    	return left+s;

  • 0
    B

    nice one, there is only one small problem, middle= len(s)//2+1; doesn;t need adding 1, middle= len(s)//2 is enough


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.