leetcode Longest Palindromic Substring

来源:互联网 发布:js escape解码 编辑:程序博客网 时间:2024/04/29 20:38

题目:

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.

方法一:

解题思路:

使用动态规划,时间复杂度为O(N²),空间复杂度也为O(N²)。
Define P[ i, j ] ← true iff the substring Si … Sj is a palindrome, otherwise false.
P[ i, j ] ← ( P[ i+1, j-1 ] and Si = Sj ) ,显然,如果一个子串是回文串,并且如果从它的左右两侧
分别向外扩展的一位也相等,那么这个子串就可以从左右两侧分别向外扩展一位。
其中的base case是
P[ i, i ] ← true
P[ i, i+1 ] ← ( Si = Si+1 )

代码:

public String longestPalindrome(String s) {        int n = s.length();        int longestBegin = 0;        int maxLength = 1;//最小长度为1,即没有回文的时候        boolean table[][] = new boolean[1000][1000];        for (int i = 0; i < 1000; i++) {            for (int j = 0; j < 1000; j++)                table[i][j] = false;        }        for (int i = 0; i < n; i++) {            table[i][i] = true;        }        for (int i = 0; i < n - 1; i++) {            if (s.charAt(i) == s.charAt(i + 1)) {                table[i][i + 1] = true;                longestBegin = i;                maxLength = 2;            }        }        for (int len = 3; len <= n; len++) {            for (int i = 0; i < n - len + 1; i++) {                int j = i + len - 1;                if (s.charAt(i) == s.charAt(j) && table[i + 1][j - 1] == true) {                    table[i][j] = true;                    longestBegin = i;                    maxLength = len;                }            }        }        return s.substring(longestBegin, longestBegin+maxLength);    }

方法二:

解题思路:

回文字符串显然有个特征是沿着中心那个字符轴对称。比如aha沿着中间的h轴对称,a沿着中间的a轴对称。那么aa呢?沿着中间的空字符''轴对称。
所以对于长度为奇数的回文字符串,它沿着中心字符轴对称,对于长度为偶数的回文字符串,它沿着中心的空字符轴对称。
对于长度为N的候选字符串,我们需要在每一个可能的中心点进行检测以判断是否构成回文字符串,这样的中心点一共有2N-1个(2N-1=N-1 + N)。
检测的具体办法是,从中心开始向两端展开,观察两端的字符是否相同。

代码:

public String expandAroundCenter(String s, int c1, int c2) {        int n = s.length();        int left = c1;        int right = c2;        while (left >= 0 && right <= n - 1 && s.charAt(left) == s.charAt(right)) {            left--;            right++;        }        return s.substring(left + 1, right);    }    public String longestPalindrome(String s) {        int n = s.length();        if (n == 0)            return "";        String longest = s.substring(0, 1);        for (int i = 0; i < n - 1; i++) {            String p1 = expandAroundCenter(s, i, i);            if (p1.length() > longest.length())//长度为奇数的                longest = p1;            String p2 = expandAroundCenter(s, i, i + 1);//长度为偶数的            if (p2.length() > longest.length())                longest = p2;        }        return longest;    }







0 0