边工作边刷题:70天一遍leetcode: day 64

Shortest Palindrome

TLE:用isPalin function肯定会超时,最好的方法是先reverse string然后再和自身比较

class Solution(object):
    def shortestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        def isPalin(s):
            i,j=0,len(s)-1
            while i<j:
                if s[i]!=s[j]:
                    return False
                i+=1
                j-=1
            return True
        s2 = s[::-1]
        n = len(s)
        for i in xrange(n):
            #if isPalin(s[:i+1]):
            if s[:n-i] == s2[i:]:
                return s2[:i]+s
        
        return ""
posted @ 2016-06-09 05:22  absolute100  阅读(73)  评论(0编辑  收藏  举报