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:

  遍历每个字符,以该字符为中心,往两边扩散寻找回文子串。应注意奇偶情况,比如"bob"是奇数形式的回文,"noon"就是偶数形式的回文,两种形式的回文都要搜索。该算法时间复杂度为O(n2)。

public class Solution {
public String longestPalindrome(String s) {
int maxBegin = 0; // 最大回文子串的起始点
int maxLength = 0; // 最大回文子串的长度
int currLength = 0; // 以当前字符为中心的回文子串长度 for (int i = 0; i < s.length() - 1; i++) {
// 以当前字符为中心寻找回文子串
currLength = searchPalindrome(s, i, i);
if (currLength > maxLength) {
maxLength = currLength;
maxBegin = i - (currLength >> 1);
}
// 如果当前字符和下一个字符相同,还应寻找以这两个字符为中心的回文子串
if (s.charAt(i) == s.charAt(i + 1)) {
currLength = searchPalindrome(s, i, i + 1);
if (currLength > maxLength) {
maxLength = currLength;
maxBegin = i + 1 - (currLength >> 1);
}
} } if (maxLength == 0) maxLength = s.length(); return s.substring(maxBegin, maxBegin + maxLength);
} public int searchPalindrome(String s, int left, int right) {
int step = 1;
while ((left - step >= 0) && (right + step < s.length())) {
if (s.charAt(left - step) != s.charAt(right + step))
break;
step++;
}
return right - left + (step << 1) - 1;
}
}

解法2:

  此题还可以用动态规划Dynamic Programming来解,我们维护一个二维数组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

  判断顺序:s[0][0] —> s[0][1] —> s[1][1] —> s[0][2] —> s[1][2] —> s[2][2] —> s[0][3] —> ....

public class Solution {
public String longestPalindrome(String s) {
boolean[][] isPal = new boolean[s.length()][s.length()];
int left = 0;
int right = 0; for (int j = 0; j < s.length(); j++) {
for (int i = 0; i < j; i++) {
isPal[i][j] = (s.charAt(i) == s.charAt(j)) && (j - i < 2 || isPal[i + 1][j - 1]);
if (isPal[i][j] && (j - i > right - left)) {
left = i;
right = j;
}
}
isPal[j][j] = true;
} return s.substring(left, right + 1);
}
}

解法3:

  最后要来的就是大名鼎鼎的马拉车算法Manacher's Algorithm,这个算法的神奇之处在于将时间复杂度提升到了O(n)这种逆天的地步,而算法本身也设计的很巧妙,很值得掌握,具体算法参见:Manacher算法总结 和 Manacher's Algorithm 马拉车算法

public class Solution {
public String longestPalindrome(String s) { // 字符串穿插"#",同时加头加尾防止越界
StringBuilder sb = new StringBuilder("@#");
for (int i = 0; i < s.length(); i++) {
sb.append(s.charAt(i)).append("#");
}
sb.append("$"); int[] len = new int[sb.length()];
int maxCenter = 0; // 记录最大回文子串的中心位置
int maxLength = 0; // 记录最大回文子串的半径
int id = 0; // 记录当前计算过的右边界所属的回文子串中心
int mx = 0; // 记录当前计算过的右边界 for (int i = 1; i < sb.length() - 1; i++) {
len[i] = i < mx ? Math.min(len[2 * id - i], mx - i + 1) : 1;
while (sb.charAt(i - len[i]) == sb.charAt(i + len[i]))
len[i]++; if (mx < i + len[i] - 1) {
mx = i + len[i] - 1;
id = i;
}
if (maxLength < len[i]) {
maxLength = len[i];
maxCenter = i;
}
}
return s.substring((maxCenter - maxLength) / 2, (maxCenter - maxLength) / 2 + maxLength - 1);
}
}

  

[LeetCode] 5. Longest Palindromic Substring ☆☆☆☆的更多相关文章

  1. LeetCode(4) || Longest Palindromic Substring 与 Manacher 线性算法

    LeetCode(4) || Longest Palindromic Substring 与 Manacher 线性算法 题记 本文是LeetCode题库的第五题,没想到做这些题的速度会这么慢,工作之 ...

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

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

  3. 求最长回文子串 - leetcode 5. Longest Palindromic Substring

    写在前面:忍不住吐槽几句今天上海的天气,次奥,鞋子里都能养鱼了...裤子也全湿了,衣服也全湿了,关键是这天气还打空调,只能瑟瑟发抖祈祷不要感冒了.... 前后切了一百零几道leetcode的题(sol ...

  4. LeetCode 5 Longest Palindromic Substring(最长子序列)

    题目来源:https://leetcode.com/problems/longest-palindromic-substring/ Given a string S, find the longest ...

  5. 【JAVA、C++】LeetCode 005 Longest Palindromic Substring

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

  6. leetcode:Longest Palindromic Substring(求最大的回文字符串)

    Question:Given a string S, find the longest palindromic substring in S. You may assume that the maxi ...

  7. [LeetCode][Python]Longest Palindromic Substring

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com'https://oj.leetcode.com/problems/longest ...

  8. 【LeetCode】Longest Palindromic Substring 解题报告

    DP.KMP什么的都太高大上了.自己想了个朴素的遍历方法. [题目] Given a string S, find the longest palindromic substring in S. Yo ...

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

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

  10. 最长回文子串-LeetCode 5 Longest Palindromic Substring

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

随机推荐

  1. CodeForces 908C. New Year and Curling 解题报告 Java

    1. 思路 这题实际上是个几何问题——两个外相切的圆,由勾股定理,他们的纵坐标有以下的规律: 则有$$y_{n+1} = y_{n} + \sqrt{(2r)^2 - (x_{n} - x_{n+1} ...

  2. Redhat linux 安装SVN服务器 CollabNetSubversionEdge

    请仔细阅读安装包自带的readme文件! ================================================= 1. 先去官网,找安装包: http://subversi ...

  3. 2.hadoop基本配置,本地模式,伪分布式搭建

    2. Hadoop三种集群方式 1. 三种集群方式 本地模式 hdfs dfs -ls / 不需要启动任何进程 伪分布式 所有进程跑在一个机器上 完全分布式 每个机器运行不同的进程 2. 服务器基本配 ...

  4. Thunder团队第一周 - Scrum会议7

    Scrum会议7 小组名称:Thunder 项目名称:爱阅app Scrum Master:宋雨 工作照片: 参会成员: 王航:http://www.cnblogs.com/wangh013/ 李传康 ...

  5. [codecademy]html&css

    1. HTML is the language used to create the web pages you visit everyday. It provides a logical way t ...

  6. iOS开发allocWithZone介绍

    首先我们知道,我们需要保证单例类只有一个唯一的实例,而平时我们在初始化一个对象的时候, [[Class alloc] init],其实是做了两件事. alloc 给对象分配内存空间,init是对对象的 ...

  7. caffe2安装教程

    相比于网上的安装教程不如直接看官方安装教程:https://caffe2.ai/docs/getting-started.html?platform=windows&configuration ...

  8. tab键、快捷键、默认按钮、小数点输入的使用--四则运算

    1. 窗体Tab键的顺序设置 选中窗体-视图-tab键顺序 label不适用tab键 2. 热键设置和快捷键设置 热键:无论光标在哪都可以 快捷键:出现界面后才能按 添加label 更改label的T ...

  9. chrome extension demos

    chrome extension demos demo https://github.com/hartleybrody/buzzkill/blob/master/bootstrap.js https: ...

  10. 第一章 Spring 概述

    Spring框架的生态,已经成了JavaWeb开发的事实标准 以IOC与AOP为基础,提供了一整套JavaWeb的开发解决方案 在需要引入功能前,先看看有没有Spring的实现,或者其他框架,看看能否 ...