作者: 负雪明烛
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] 是否为回文串。

  1. 当 i = j 时,只有一个字符,肯定是回文串;
  2. 如果 i = j + 1 ,说明是相邻字符,此时需要判断 s[i]是否等于 s[j] ;
  3. 如果 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 最长回文子串的更多相关文章

  1. Leetcode 5. Longest Palindromic Substring(最长回文子串, Manacher算法)

    Leetcode 5. Longest Palindromic Substring(最长回文子串, Manacher算法) Given a string s, find the longest pal ...

  2. [LeetCode] 5. Longest Palindromic Substring 最长回文子串

    Given a string s, find the longest palindromic substring in s. You may assume that the maximum lengt ...

  3. [leetcode]5. Longest Palindromic Substring最长回文子串

    Given a string s, find the longest palindromic substring in s. You may assume that the maximum lengt ...

  4. LeetCode:Longest Palindromic Substring 最长回文子串

    题目链接 Given a string S, find the longest palindromic substring in S. You may assume that the maximum ...

  5. lintcode :Longest Palindromic Substring 最长回文子串

    题目 最长回文子串 给出一个字符串(假设长度最长为1000),求出它的最长回文子串,你可以假定只有一个满足条件的最长回文串. 样例 给出字符串 "abcdzdcab",它的最长回文 ...

  6. 5. Longest Palindromic Substring(最长回文子串 manacher 算法/ DP动态规划)

    Given a string s, find the longest palindromic substring in s. You may assume that the maximum lengt ...

  7. 1. Longest Palindromic Substring ( 最长回文子串 )

    要求: Given a string S, find the longest palindromic substring in S. (从字符串 S 中最长回文子字符串.) 何为回文字符串? A pa ...

  8. 【翻译】Longest Palindromic Substring 最长回文子串

    原文地址: http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-i.html 转载请注明出处:http:// ...

  9. 005 Longest Palindromic Substring 最长回文子串

    Given a string s, find the longest palindromic substring in s. You may assume that the maximum lengt ...

随机推荐

  1. pyyaml模块

    pyyaml模块是一种文件数据处理格式的方法,常用与生成.解析或修改.yaml配置文件 1.常见.yaml文件格式内容如下 languages: - Ruby - Perl - Python webs ...

  2. 类成员函数调用delete this会发生什么呢?

    有如下代码 class myClass { public: myClass(){}; ~myClass(){}; void foo() { delete this; } }; int main() { ...

  3. 【模板】单源最短路径(Dijkstra)/洛谷P4779

    题目链接 https://www.luogu.com.cn/problem/P4779 题目大意 给定一个 \(n\) 个点 \(m\) 条边有向图,每个点有一个非负权值,求从 \(s\) 点出发,到 ...

  4. c#表格序号列

    <asp:BoundField HeaderText="序号" /> OnRowCreated="gridview_RowCreated" prot ...

  5. javaSE高级篇6 — 注解( 附:注解底层解析 ) —— 更新完毕

    注解 ---- 英文:annotation 1.注解长什么样子? @xxxxxxx( 一些信息 ) ----- 这个信息可有可无 2.注解可以放在什么地方? 类本身的上面.属性的上面.方法的上面.参数 ...

  6. Spark Stage 的划分

    Spark作业调度 对RDD的操作分为transformation和action两类,真正的作业提交运行发生在action之后,调用action之后会将对原始输入数据的所有transformation ...

  7. h5移动端设备像素比dpr介绍

    首先介绍一下概念 devicePixelRatio其实指的是window.devicePixelRatio window.devicePixelRatio是设备上物理像素和设备独立像素(device- ...

  8. 【leetcode】986. Interval List Intersections (双指针)

    You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, ...

  9. 编程之美Q1

    题目 和数书页有点类似,就直接数吧 #include<iostream> using namespace std; class q1 { public: size_t func(size_ ...

  10. Spring的事务传播机制(通俗易懂)

    概述 Spring的事务传播机制有7种,在枚举Propagation中有定义. 1.REQUIRED PROPAGATION_REQUIRED:如果当前没有事务,就创建一个新事务,如果当前存在事务,就 ...