zoukankan      html  css  js  c++  java
  • 5. Longest Palindromic Substring 最长的回文子串

    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"
    

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    class Solution1:
        def longestPalindrome(self, s):
            """
            :type s: str
            :rtype: str
            """
            res = ""
            for i in range(len(s)):
                j = i + len(res) + 1
                while j <= len(s):
                    cur = s[i:j]
                    if len(cur) > len(res) and cur == cur[::-1]:
                        res = cur
                    j += 1
            return res
     
     
    class Solution2:
        def longestPalindrome(self, s):
            if len(s) == 0:
                return ""
            maxLen = 1
            start = 0
            for i in range(len(s)):
                cur = s[i - maxLen - 1:i + 1]
                if i - maxLen >= 1 and cur == cur[::-1]:
                    start = i - maxLen - 1
                    maxLen += 2
                    continue
     
                cur = s[i - maxLen:i + 1]
                if i - maxLen >= 0 and cur == cur[::-1]:
                    start = i - maxLen
                    maxLen += 1
     
            return s[start:start + maxLen]
     
     
    s = "babad"
    #s = "cbbd"
    solution = Solution2()
    res = solution.longestPalindrome(s)
    # print(res)







  • 相关阅读:
    后端PHP框架laravel学习踩的各种坑
    IE6、IE7兼容querySelectorAll和querySelector方法-最终版本
    package.json保存
    原生javascript兼容性总结
    原生javascript代码懒加载
    禁止选择文本样式
    xml转实体类的实现
    kendo ui editor 文本编辑器 自定义高度的实现
    setTimeout执行时带参数,并且带的是object对象类型的参数
    KendoUi listview template的用法记录
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/8445814.html
Copyright © 2011-2022 走看看