1.(字符串)-获取字符串的最长回文子串

如:'abcdzdcab',返回:cdzdc

'abcdzdcab111',返回:cdzdc

python:

# 1穷举
class Solution:
    def str(self, s):
        if not s:
            return ''
        n = len(s)
        logest, left, right = 0, 0, 0    #最大回文长度,最大回文左右位置
        for i in range(0, n):
            for j in range(i + 1, n + 1):
                substr = s[i:j]    #截取i:j的子串,判断子串是不是回文,且标记最大回文
                if self.isPalindrome(substr) and len(substr) > logest:
                    logest = len(substr)
                    left, right = i, j
        return s[left:right]

    def isPalindrome(self, s):
        if not s:
            return False
        #仅考虑纯字母,[::-1]反转字符
        return s == s[::-1]

#2,分奇偶情况,对称判定。
class Solution2:
    def str(self, s):
        if s == None or len(s) == 0:
            return s
        res = ''
        for i in range(len(s)):
            # 奇数情况,左右都是i开始,为对称轴两边取字母延伸
            t = self.pali(s, i, i)
            #保留最大回文串
            if len(t) > len(res):
                res = t
            #     偶数情况
            t = self.pali(s, i, i + 1)
            if len(t) > len(res):
                res = t
        return res

    def pali(self, s, l, r):
        #只要左边l,右边r不到顶端,且左右位置字母相等,就一直遍历
        while l >= 0 and r < len(s) and s[l] == s[r]:
            l -= 1
            r += 1
        #返回l,r两边扩展寻找回文字符串
        return s[l + 1:r]


s = Solution()
# s2 = Solution2()
print(s.str('abcdzdcab'))
# print(s2.str('abcdzdcab111'))

 

posted @ 2019-02-12 21:09  jj千寻  阅读(120)  评论(0编辑  收藏  举报