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. aishell数据处理为thchs30格式

    目录 aishell数据转换格式 aishell数据转化方法 aishell数据格式对于用神经网络处理数据的同学来说比较不友善,因为他只有文字转录和音素级别的转录,并没有拼音的转录. 而thchs30 ...

  2. Eclipse 安装SVN、Maven插件

    1先安装subeclipse插件就是svn svn - http://subclipse.tigris.org/update_1.6.x 我这里是灰色的说明我安装过了这里只是截图说明下,我就不继续安装 ...

  3. Bus of Characters(栈和队列)

    In the Bus of Characters there are nn rows of seat, each having 22 seats. The width of both seats in ...

  4. MyBatis 基本构成与框架搭建

    核心组件 SqlSessionFactoryBuilder (构造器) 根据配置信息(eg:mybatis-config.xml)或者代码来生成SqlSessionFactory. SqlSessio ...

  5. 【数位DP】题集

    1.[HDOJ2089] 题意:求区间内不出现4和62的数的个数 解法:模板题 2.[HDOJ3555] 题意:求区间内不出现49的数的个数 解法:模板题 3.[HDOJ5179] 题意:对于一个十进 ...

  6. eg_2

    2. 编写一个程序,输出在一个字符串中,指定的字符串出现的次数 第一种方法: public class Test { public static void main(String[] args) { ...

  7. 爬虫之手机APP抓包教程-亲测HTTP和HTTPS均可实现

    当下很多网站都有做自己的APP端产品,一个优秀的爬虫工程师,必须能够绕过难爬取点而取捷径,这是皆大欢喜的.但是在网上收罗和查阅了无数文档和资料,本人亲测无数次,均不能正常获取HTTPS数据,究其原因是 ...

  8. dev_queue_xmit 发生了什么?skb还会在哪里缓存

    见 codebox/net/qdisk/xmit.log中保存了一份记录 调用关系 sch_direct_xmit --> dev_hard_start_xmit --> xmit_one ...

  9. Dubbo和Spring Cloud开发框架对比

    前言 微服务架构是互联网很热门的话题,是互联网技术发展的必然结果.它提倡将单一应用程序划分成一组小的服务,服务之间互相协调.互相配合,为用户提供最终价值.虽然微服务架构没有公认的技术标准和规范或者草案 ...

  10. 【Json】C#格式化JSON字符串

    很多时候我们需要将json字符串以 {     "status": 1,     "sum": 9 }这种方式显示,而从服务端取回来的时候往往是这样 {&quo ...