LeetCode:Longest Palindromic Substring


2018-05-19 17:59:37 by sikoay with 0 comments 1 Hits
Blog 1

代码


class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        current =  0
        result = ''
        while current < len(s):
            result1 = self.substring1(s,current)
            result2 = self.substring2(s,current)
            curresult = result1 if len(result1) > len(result2) else result2
            if(len(curresult) > len(result)):
                result = curresult
            current += 1
        return result

    def substring1(self,s,cur):
        result = ''
        sublen = 1
        subnum = cur -1
        while True:
            if  cur >= len(s) or subnum<0:
                break
            if  s[cur] == s[subnum]:
                result = s[cur] + result + s[cur]
                subnum -= 1
                cur += 1
            else:
                break
        return result;

    def substring2(self,s,cur):
        result = s[cur];
        sublen = 1
        cur = cur+1
        subnum = cur -2
        while True:
            if  cur >= len(s) or subnum<0:
                break
            
            if  s[cur] == s[subnum]:
                result = s[cur] + result + s[cur]
                subnum -= 1
                cur += 1
            else:
                break
        return result;

    def substring1(self,s,cur):
        result = ''
        sublen = 1
        subnum = cur -1
        while True:
            if  cur >= len(s) or subnum<0: break if s[cur] == s[subnum]: result = s[cur] + result + s[cur] subnum -= 1 cur += 1 else: break return result; def substring2(self,s,cur): result = s[cur]; sublen = 1 cur = cur+1 subnum = cur -2 while True: if cur >= len(s) or subnum<0: break if s[cur] == s[subnum]: result = s[cur] + result + s[cur] subnum -= 1 cur += 1 else: break return result;



性能比较差...

Tags:

回复 (0)

Leave a Comment