【LeetCode】5. Longest Palindromic Substring 最长回文子串
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
公众号:负雪明烛
本文关键词:最长回文子串,题解,leetcode, 力扣,python, C++, java
题目地址:https://leetcode.com/problems/longest-palindromic-substring/description/
题目描述
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"
题目大意
找出字符串中最长的回文子串。
解题方法
暴力遍历
遍历算法是我们最直观的解法,事实上也能通过OJ。我们使用的方法是两重循环确定子串的起始和结束位置,这样只要判断该子串是个回文,我们保留最长的回文即可。
代码很简单,C++版本如下:
class Solution {
public:
string longestPalindrome(string s) {
const int N = s.size();
string res;
for (int i = 0; i < N; i++) {
for (int j = i; j < N; j++) {
if (j - i + 1 >= res.size() && isPalindrome(s, i, j)) {
res = s.substr(i, j - i + 1);
}
}
}
return res;
}
// [start, end]
bool isPalindrome(string& s, int start, int end) {
const int N = s.size();
int l = start, r = end;
while (l <= r) {
if (s[l++] != s[r--]) {
return false;
}
}
return true;
}
};
动态规划
动态规划的两个特点:第一大问题拆解为小问题,第二重复利用之前的计算结果,来解答这道题。
那如何划分小问题呢,我们可以先把所有长度最短为1的子字符串计算出来,根据起始位置从左向右,这些必定是回文。然后计算所有长度为2的子字符串,再根据起始位置从左向右。到长度为3的时候,我们就可以利用上次的计算结果:如果中心对称的短字符串不是回文,那长字符串也不是,如果短字符串是回文,那就要看长字符串两头是否一样。这样,一直到长度最大的子字符串,我们就把整个字符串集穷举完了。
我们维护一个二维数组 dp
,其中 dp[i][j]
表示字符串区间 [i, j]
是否为回文串。
- 当
i = j
时,只有一个字符,肯定是回文串; - 如果
i = j + 1
,说明是相邻字符,此时需要判断s[i]
是否等于s[j]
; - 如果
i
和j
不相邻,即i - j >= 2
时,除了判断s[i]
和s[j]
相等之外,dp[j + 1][i - 1]
若为真,就是回文串。
通过以上分析,可以写出递推式如下:
dp[i, j] = 1 if i == j
= s[i] == s[j] if j = i + 1
= s[i] == s[j] && dp[i + 1][j - 1] if j > i + 1
Python 代码刚提交的时候超时了,但是使用set一下,看看是否只包含相同字符,这样就通过了!
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if len(set(s)) == 1: return s
n = len(s)
start, end, maxL = 0, 0, 0
dp = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(i):
dp[j][i] = (s[j] == s[i]) & ((i - j < 2) | dp[j + 1][i - 1])
if dp[j][i] and maxL < i - j + 1:
maxL = i - j + 1
start = j
end = i
dp[i][i] = 1
return s[start : end + 1]
C++版本代码如下,需要注意的是这里的res初始化为第一个字符:
class Solution {
public:
string longestPalindrome(string s) {
const int N = s.size();
if (N == 0) return "";
string res = s.substr(0, 1);
vector<vector<bool>> dp(N, vector(N, false));
// s[j, i]
for (int i = 0; i < N; i++) {
for (int j = 0; j < i; j++) {
dp[j][i] = (s[j] == s[i]) && (i == j + 1 || dp[j + 1][i - 1]);
if (dp[j][i] && i - j + 1 >= res.size()) {
res = s.substr(j, i - j + 1);
}
}
dp[i][i] = true;
}
return res;
}
};
二刷—
马拉车算法。。待续
参考:
http://www.cnblogs.com/grandyang/p/4464476.html
https://segmentfault.com/a/1190000002991199
日期
2018 年 3 月 15 日 —— 雾霾消散,春光明媚
2019 年 1 月 19 日 —— 有好几天没有更新文章了
【LeetCode】5. Longest Palindromic Substring 最长回文子串的更多相关文章
- Leetcode 5. Longest Palindromic Substring(最长回文子串, Manacher算法)
Leetcode 5. Longest Palindromic Substring(最长回文子串, Manacher算法) Given a string s, find the longest pal ...
- [LeetCode] 5. Longest Palindromic Substring 最长回文子串
Given a string s, find the longest palindromic substring in s. You may assume that the maximum lengt ...
- [leetcode]5. Longest Palindromic Substring最长回文子串
Given a string s, find the longest palindromic substring in s. You may assume that the maximum lengt ...
- LeetCode:Longest Palindromic Substring 最长回文子串
题目链接 Given a string S, find the longest palindromic substring in S. You may assume that the maximum ...
- lintcode :Longest Palindromic Substring 最长回文子串
题目 最长回文子串 给出一个字符串(假设长度最长为1000),求出它的最长回文子串,你可以假定只有一个满足条件的最长回文串. 样例 给出字符串 "abcdzdcab",它的最长回文 ...
- 5. Longest Palindromic Substring(最长回文子串 manacher 算法/ DP动态规划)
Given a string s, find the longest palindromic substring in s. You may assume that the maximum lengt ...
- 1. Longest Palindromic Substring ( 最长回文子串 )
要求: Given a string S, find the longest palindromic substring in S. (从字符串 S 中最长回文子字符串.) 何为回文字符串? A pa ...
- 【翻译】Longest Palindromic Substring 最长回文子串
原文地址: http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-i.html 转载请注明出处:http:// ...
- 005 Longest Palindromic Substring 最长回文子串
Given a string s, find the longest palindromic substring in s. You may assume that the maximum lengt ...
随机推荐
- keil 报错 expected an identifier
该报错是因为命名重复,可能是因为你加的头文件里面的命名和原程序中的有重复,所以产生了错误.
- Linux系统根目录下各文件夹介绍
参考自:[1]Linux 系统根目录下各个文件夹的作用 https://www.cnblogs.com/jiangfeilong/p/10538795.html[2]了解Linux根目录"/ ...
- 事务(@Transactional注解)的用法和实例
参数 @Transactional可以配制那些参数及以其所代表的意义: 参数 意义 isolation 事务隔离级别 propagation 事务传播机制 readOnly 事务读写性 noRollb ...
- Turbine使用
一.简介 Turbine是聚合服务器发送事件流数据的一个工具,Hystrix的监控中,只能监控单个节点,实际生产中都为集群,因此可以通过Turbine来监控集群下Hystrix的metrics情况 T ...
- Thymeleaf+layui+jquery复选框回显
一.Thymeleaf+layui+jquery复选框回显 基于Thymeleaf模板下的layui+jquery复选框回显,主要是jquery.大致意思是:把数组转成JSON传到前台,再在前台转回数 ...
- matplotlib animation
import numpy as np from matplotlib import pyplot as plt from matplotlib import animation fig, ax = p ...
- 并行Louvain社区检测算法
因为在我最近的科研中需要用到分布式的社区检测(也称为图聚类(graph clustering))算法,专门去查找了相关文献对其进行了学习.下面我们就以这篇论文IPDPS2018的文章[1]为例介绍并行 ...
- JSP九大内置对象及四个作用域详解
一共有九大内置对象: request.response.out.session.application.pageContext.page.config.exception 内置对象(又叫隐含对象),就 ...
- redis迁移工具redis-migrate-tool
目录 一.简介 二.测试 三.安装 四.验证 一.简介 redis-migrate-tool是在redis之间迁移数据的一个方便且有用的工具.他会已服务方式不断同步两边的数据.等到合适时间,中断red ...
- Apache log4j2-RCE 漏洞复现(CVE-2021-44228)
Apache log4j2-RCE 漏洞复现 0x01 漏洞简介 Apache Log4j2是一个基于Java的日志记录工具.由于Apache Log4j2某些功能存在递归解析功能,攻击者可直接构造恶 ...