Longest Palindromic Substring

来源:互联网 发布:linux finger 命令 编辑:程序博客网 时间:2024/06/05 23:23

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

Example

Given the string = "abcdzdcab", return "cdzdc".

Challenge 

O(n2) time is acceptable. Can you do it in O(n) time.

O(n^2): for example: “a”, transfer “a”to “#a#”, “ab”, transfer “ab” to “#a#b#”. This step transfer all string to oddlength. Then traverse all string, every time set a count equals one. This countmeans the length you extend to left and right side. while (i - count >= 0&& i + count <= len + 1 && (getChar(s, i - count) ==getChar(s, i + count))), you should continue extend substring. For getChar function,if (i%2 == 0), return ‘#’, else return s(i/2). Back to the main function, comparemax with count and update substring. If you cannot sure the parameter in codelike i, i + 1, (i+count)/2, you can use “a” as example to determine it. Code as following:

public class Solution {    /**     * @param s input string     * @return the longest palindromic substring     */    public String longestPalindrome(String s) {        // Write your code here        int max = 0, len = s.length() * 2 - 1;        String res = "";        for (int i = 1; i <= len; i ++) {            int count = 1;            while (i - count >= 0 && i + count <= len + 1 && (getChar(s, i - count) == getChar(s, i + count))) {                count ++;            }            count --;            if (max < count) {                max = count;                res = s.substring((i - count) / 2, (i + count) / 2);            }        }        return res;    }        private char getChar(String s, int i) {        if (i % 2 == 0) {            return '#';        } else {            return s.charAt(i / 2);        }    }}

O(n): Manacher's Algorithm: …….




原创粉丝点击