200.Longest Palindromic Substring-最长回文子串(中等题)

来源:互联网 发布:韩国迷你网络剧 编辑:程序博客网 时间:2024/05/17 09:39

最长回文子串

  1. 题目

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

  2. 样例

    给出字符串 “abcdzdcab”,它的最长回文子串为 “cdzdc”。

  3. 挑战

    O(n^2) 时间复杂度的算法是可以接受的,如果你能用 O(n) 的算法那自然更好。

  4. 题解

    Manacher算法,时间复杂度为O(n)。

public class Solution {    /**     * @param s input string     * @return the longest palindromic substring     */    public String longestPalindrome(String s) {        if (s == null || s.length() == 0)         {            return "";        }        int length = s.length();            int max = 0;        String result = "";        for(int i = 1; i <= 2 * length - 1; i++)        {            int count = 1;            while(i - count >= 0 && i + count <= 2 * length  && get(s, i - count) == get(s, i + count))            {                count++;            }            count--;             if(count > max)             {                result = s.substring((i - count) / 2, (i + count) / 2);                max = count;            }        }        return result;    }    private char get(String s, int i)     {        return i % 2 == 0 ? '#' : s.charAt(i / 2);    }}

Last Update 2016.11.2

0 0
原创粉丝点击