[编程练习]Longest Palindromic Substring <LeetCode-5>

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.


题目来自: https://oj.leetcode.com/problems/longest-palindromic-substring/


这一题是求一个字符串(长度<=1000)中最长的回文子串(题目限定只有唯一一个)。难度标注为"Medium"

我想这题也比较简单,思路就是完整扫描,遇到有回文可能的位置开始左右观察。记录最大值。 

class Solution:
    # @return a string
    def longestPalindrome(self, s):
        lenstr = len(s)
        maxlen = 1
        maxstart, maxend = 0, 0
        
        #向左向右比较确定是否回文
        def scancmp(s, start, end):
            while ((start - 1 >= 0) and (end + 1 <= lenstr - 1)):
                if s[start - 1] != s[end + 1]:
                    break
                start -= 1
                end += 1
            return start, end            
        
        for i in range(1, lenstr):
            #回文形式'aba'
            if (i < lenstr - 1) and s[i + 1] == s[i - 1]:
                start, end = scancmp(s, i - 1, i + 1)
                if (end + 1 - start) > maxlen:
                    maxlen, maxstart, maxend = (end + 1 -start), start, end   
            #回文形式'aa'                
            if s[i] == s[i - 1]:
                start, end = scancmp(s, i - 1, i)   
                if (end + 1 - start) > maxlen:
                    maxlen, maxstart, maxend = (end + 1 -start), start, end                 
             
        return s[maxstart:maxend + 1]


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值