[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 ...
 
随机推荐
- 创新手机游戏《3L》开发点滴(1)——道具、物品、装备表设计
			
一.游戏物品/道具系统数据模型设计特点 为了让游戏更加的丰富,我们1201团队的新手机游戏设计了道具系统.于是丰富了游戏.取悦了玩家,哭了开发——道具/物品数据子系统是简单的.复杂的.不确定的: 简单 ...
 - nodejs反向代理插件anyproxy安装
			
目前我使用的是Anyproxy,AnyProxy .这个软件的特点是可以获取到https链接的内容.在2016年年初的时候微信公众号和微信文章开始使用https链接.并且Anyproxy可以通过修改r ...
 - codeforces 359E Neatness(DFS+构造)
			
Simon loves neatness. So before he goes to bed, Simon wants to complete all chores in the house. Sim ...
 - 【转】MySQLroot用户忘记密码解决方案(安全模式,修改密码的三种方式)
			
文章出自:http://www.2cto.com/database/201412/358128.html 1.关闭正在运行的MySQL2.启动MySQL的安全模式,命令如下: ? 1 mysqld - ...
 - python异步初步窥探
			
1.异步之难:因为其执行吮吸不可预料,当下正要发生什么事件不可预料. 程序下一步行为往往依赖上一步值执行结果,如何知晓上次异步调用已完成并获取结果, 回调成了必然选择,那又 ...
 - ZooKeeper server &&client
			
写了一个关于zookeepeer应用的简单demo 服务端定时的向zookeeper集群注册,客户端监听zookeeper服务节点变化,一旦变化,立刻响应,更新服务端列表 服务端代码: #includ ...
 - iOS- 多线程技术的概述及优点
			
1.概述 在iOS开发中: •耗时操作,例如网络图片.视频.歌曲.书籍等资源下载 •游戏中的声音播放 我们可以利用多线程: •充分发挥多核处理器的优势,并发(同时执行)执行任务让系统运行的更快.更 ...
 - <Effective C++>读书摘要--Designs and Declarations<二>
			
<Item 20> Prefer pass-by-reference-to-const to pass-by-value 1.By default, C++ passes objects ...
 - Personal summary 个人总结
			
一.请回望开学时的第一次作业,你对于软件工程课程的想象 对比开篇博客你对课程目标和期待,"希望通过实践锻炼,增强计算机专业的能力和就业竞争力",对比目前的所学所练所得,在哪些方面达 ...
 - 从1到n的阶乘的和(python)
			
今天在百度上逛一些ctf的平台,偶然发现一道编程题,于是乎,便用我刚刚学的python知识解了这道题 题目的描述是这样的: 计算1!+2!+3!+...+6666!后五位. 这个计算量很大啊,我还是用 ...