[LeetCode] 5. Longest Palindromic Substring ☆☆☆☆
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 ☆☆☆☆的更多相关文章
- LeetCode(4) || Longest Palindromic Substring 与 Manacher 线性算法
LeetCode(4) || Longest Palindromic Substring 与 Manacher 线性算法 题记 本文是LeetCode题库的第五题,没想到做这些题的速度会这么慢,工作之 ...
- 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
写在前面:忍不住吐槽几句今天上海的天气,次奥,鞋子里都能养鱼了...裤子也全湿了,衣服也全湿了,关键是这天气还打空调,只能瑟瑟发抖祈祷不要感冒了.... 前后切了一百零几道leetcode的题(sol ...
- LeetCode 5 Longest Palindromic Substring(最长子序列)
题目来源:https://leetcode.com/problems/longest-palindromic-substring/ Given a string S, find the longest ...
- 【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 ...
- leetcode:Longest Palindromic Substring(求最大的回文字符串)
Question:Given a string S, find the longest palindromic substring in S. You may assume that the maxi ...
- [LeetCode][Python]Longest Palindromic Substring
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com'https://oj.leetcode.com/problems/longest ...
- 【LeetCode】Longest Palindromic Substring 解题报告
DP.KMP什么的都太高大上了.自己想了个朴素的遍历方法. [题目] Given a string S, find the longest palindromic substring in S. Yo ...
- [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 ...
随机推荐
- Machine Learning分类:监督/无监督学习
从宏观方面,机器学习可以从不同角度来分类 是否在人类的干预/监督下训练.(supervised,unsupervised,semisupervised 以及 Reinforcement Learnin ...
- dice2win早期版本
原理; https://medium.com/dapppub/fairdicedesign-315a4e253ad6 早期版本地址: https://etherscan.io/address/0xD1 ...
- zabbix 2.2.2 安装部署
zabbix 2.2.2版本与1.8.3版本安装过程略有不同,下面为实施步骤: 服务端:172.16.1.61 客户端:172.16.1.8 搭建zbbix软件 安装LAMP环境及依赖包 [root@ ...
- nodejs笔记--mysql篇(四)
测试连接 var mysql = require('mysql'); //调用MySQL模块 //创建一个connection var connection = mysql.createConnect ...
- 寒假作业end
开始写博客的个人体会 自己打的链表过不了,果然,心存侥幸是不行的,被揪出来也不错,很感谢畅畅酱. 学术诚信的重要性 爱因斯坦说过:"大多数人说是才智造就了伟大的科学家,他们错了,是人格.&q ...
- LintCode-371.用递归打印数字
用递归打印数字 用递归的方法找到从1到最大的N位整数. 注意事项 用下面这种方式去递归其实很容易: recursion(i) { if i > largest number: return re ...
- ZOJ 2110 C - Tempter of the Bone
https://vjudge.net/contest/67836#problem/C The doggie found a bone in an ancient maze, which fascina ...
- 关于houghlines函数角度问题的说明
以上是opecv reference里面的说明. Image必须是8位单通道图(可以使灰度图.二值图.边缘图等) Rho:距离分辨率,一般为1 Theta:角度分辨率,一般为CV_PI/180 Thr ...
- 2017 ICPC beijing E - Cats and Fish
#1631 : Cats and Fish 时间限制:1000ms 单点时限:1000ms 内存限制:256MB 描述 There are many homeless cats in PKU camp ...
- 【题解】Atcoder AGC#16 E-Poor Turkeys
%拜!颜神怒A此题,像我这样的渣渣只能看看题解度日╭(╯^╰)╮在这里把两种做法都记录一下吧~ 题解做法:可以考虑单独的一只鸡 u 能否存活.首先我们将 u 加入到集合S.然后我们按照时间倒序往回推, ...