Leetcode篇:最长回文子串


@author: ZZQ
@software: PyCharm
@file: longestPalindrome.py
@time: 2018/9/18 20:06
要求:给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。
e.g.: 输入: "babad"
输出: "bab"
注意: "aba"也是一个有效答案。

        输入: "cbbd"
        输出: "bb"

思路:two pointer方法,考虑偶数子串和奇数子串两种可能。 从第一个字符开始,向左向右扫描,直到越界或是不满足对称要求,记录每次回文的长度和回文,保留最长的回文

class Solution():
    def __init__(self):
        pass

    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        sub_len = 0
        sub_longest_str = ""
        for i in range(0, len(s)):
            left = i-1
            right = i+1
            current_len = 1
            while left >= 0 and right < len(s):
                    if s[left] != s[right]:
                        break
                    current_len += 2
                    left -= 1
                    right += 1
            if current_len > sub_len:
                    sub_longest_str = s[left+1: right]
                    sub_len = current_len
            left = i - 1
            right = i
            current_len = 0
            while left >= 0 and right < len(s):
                    if s[left] != s[right]:
                        break
                    current_len += 2
                    left -= 1
                    right += 1
            if current_len > sub_len:
                    sub_longest_str = s[left+1: right]
                    sub_len = current_len
        return sub_longest_str


if __name__ == "__main__":
    answer = Solution()
    print answer.longestPalindrome("a")  # "cbbd"

猜你喜欢

转载自www.cnblogs.com/zzq-123456/p/9671349.html