LeetCode-algorithms 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、个数为偶数,整个字符串两边对称。根据遍历重文的思路,从一个位置开始向两边遍历,看是否两边的字符相等,去找整个重文的长度。因此除了要遍历每一个字符的两边意外,还要遍历两个字符中间位置的两边 是否相等,因此为了简便处理,我现在在本来字符串的基础上加入一个特殊的字符:空格;如本来是“abc”的,我处理完后就变成了“ a b c ”,这样我除了检查a b c三个字符以外,还要检查空格的两边是否相等,整个字符的长度变成了2n+1。每一个位置都去遍历两边寻找整个重文串,遇到空格跳过,当找到一个比记录的重文串要长的时候就重新记录最长的重文串,最后得出结果


代码:

class Solution(object):
    def longestPalindrome(self, s):
        if len(s) == 1 or len(s) == 0:
            return s
        newString = " "
        for string in s:
            newString +=string + " "
        check = []
        ans = s[0]
        for i in range(1,len(newString)-2):
            j = 0
            if newString[i] == " ":
                candidate = ""
            else:
                candidate = ""+newString[i]
            while True:
                j += 1
                if i-j >=0 and j+i < len(newString) and (newString[i-j] == newString[i+j]):
                    if newString[i+j] == " ":
                        continue
                    candidate = newString[i-j] + candidate + newString[i+j]
                else:
                    if j != 1 and j != 2:
                        if len(candidate) > len(ans):
                            ans = candidate
                    break
        return ans


结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值