• (python)leetcode刷题笔记05 Longest Palindromic Substring


    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 class Solution:
     2     def solve(self,s,l,r):
     3         while r<len(s) and l>=0 and s[l]==s[r]:
     4             l-=1
     5             r+=1
     6         return s[l+1:r]
     7     def longestPalindrome(self,s):
     8         if len(s) == 0:
     9             return 0
    10         max_string=''
    11         for i in range(len(s)):
    12             #奇数长度回文串如ababa
    13             tmp=self.solve(s,i,i)
    14             if len(tmp)>len(max_string):
    15                 max_string=tmp
    16             #偶数回文串如abba
    17 
    18             tmp=self.solve(s,i,i+1)
    19             if len(tmp)>len(max_string):
    20                 max_string=tmp
    21 
    22         return max_string
    Code
     1 def solve(s,l,r):
     2     while r<len(s) and l>=0 and s[l]==s[r]:
     3         l-=1
     4         r+=1
     5     return s[l+1:r]
     6 def longestPalindrome(s):
     7     if len(s) == 0:
     8         return 0
     9     max_string=''
    10     for i in range(len(s)):
    11         #奇数长度回文串如ababa
    12         tmp=solve(s,i,i)
    13         if len(tmp)>len(max_string):
    14             max_string=tmp
    15         #偶数回文串如abba
    16 
    17         tmp=solve(s,i,i+1)
    18         if len(tmp)>len(max_string):
    19             max_string=tmp
    20 
    21     return max_string
    22 
    23 
    24 
    25 
    26 print(longestPalindrome('ababa'))
    Debug Code
  • 相关阅读:
    降龙十八掌之三:(见龙在田)优化查询性能
    完整的项目工程目录结构
    降龙十八掌之一:(亢龙有悔)SQL Server Profiler和数据库引擎优化顾问
    ASP.NET状态管理的总结
    LINQ 图解
    获取IP城市
    Eclipse 编译StanfordNLP
    Centos JAVA Eclipse
    关掉PUTTY后,进程仍可以运行。
    centos lnmp 安装笔记
  • 原文地址:https://www.cnblogs.com/qflyue/p/8329883.html
Copyright © 2020-2023  润新知