leetcode: 5. Longest Palindromic Substring

来源:互联网 发布:微信小游戏源码下载 编辑:程序博客网 时间:2024/06/14 15:58

Problem

# Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.## Example:## Input: "babad"## Output: "bab"## Note: "aba" is also a valid answer.## Example:## Input: "cbbd"## Output: "bb"

AC

class Solution():    def longestPalindrome(self, s):        if len(s) == 1:            return s        longest = ""        for i in range(len(s)-1):            args = [(s, i, i), (s, i, i + 1)]            for arg in args:                tmp = self.longestPalindromeByAxis(*arg)                if len(tmp) > len(longest):                    longest = tmp        return longest    def longestPalindromeByAxis(self, s, left, right):        while left >= 0 and right < len(s) and s[left] == s[right]:            left, right = left - 1, right + 1        return s[left + 1: right]if __name__ == "__main__":    assert Solution().longestPalindrome("a") == 'a'    assert Solution().longestPalindrome("babad") == 'bab'    assert Solution().longestPalindrome("cbbd") == 'bb'    assert Solution().longestPalindrome("VABBCBBAS") == 'ABBCBBA'


原创粉丝点击