博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode005. Longest Palindromic Substring
阅读量:2241 次
发布时间:2019-05-09

本文共 1208 字,大约阅读时间需要 4 分钟。

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"Output: "bab"Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"Output: "bb"

思路:以每一个字母为中心,向两边寻找;或者以两个字母为中心向两边寻找。

class Solution(object):    def longestPalindrome(self, s):        """        :type s: str        :rtype: str        """        maxi=0        l=0        r=0        def helper(s,l,r):            while l>=0 and r
maxi: maxi = length1 l,r=l1,r1 if length2>maxi: maxi = length2 l,r=l2,r2 return s[l:r+1]

第一次写的时候两边界线出错。 在helper写中的是while l>0.这样从第一个字母开始回文就会出错。另外l>=0时,对应最后的s[l+1,r]

还有用dp算法,比较复杂,详情参考

class Solution(object):    def longestPalindrome(self, s):        if len(s)<2: return s        maxlen=0        result=''        dp = [[0]*len(s) for i in range(len(s))]        for j in range(len(s)):            for i in range(j+1):                dp[i][j] = (s[i]==s[j]) and (j-i<=2 or dp[i+1][j-1])                if dp[i][j]:                    if maxlen < j-i+1:                        maxlen = j-i+1                        result = s[i:j+1]        return result

 

转载地址:http://ubrbb.baihongyu.com/

你可能感兴趣的文章
【MyBatis学习06】输入映射和输出映射
查看>>
【MyBatis学习07】动态sql
查看>>
【MyBatis学习08】高级映射之一对一查询
查看>>
【MyBatis学习09】高级映射之一对多查询
查看>>
【MyBatis学习10】高级映射之多对多查询
查看>>
【MyBatis学习11】MyBatis中的延迟加载
查看>>
【MyBatis学习12】MyBatis中的一级缓存
查看>>
【MyBatis学习13】MyBatis中的二级缓存
查看>>
【MyBatis学习14】MyBatis和Spring整合
查看>>
【MyBatis学习15】MyBatis的逆向工程生成代码
查看>>
Java 中 final、finally 和 finalize 使用总结
查看>>
volatile关键字解析
查看>>
单例模式的八种写法比较
查看>>
比较常见的数据库SQL面试题以及答案
查看>>
MySQL与Oracle的区别
查看>>
关于Oracle数据库优化的几点总结
查看>>
69道Spring面试题和答案
查看>>
40个Java多线程问题总结
查看>>
Oracle数据库面试题
查看>>
java面试中的智力题
查看>>