动态规划-5-最长回文子串

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LaputaFallen/article/details/79922510

Description:

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"

问题描述

找出字符串s的最长回文子串


问题分析

这种找出回文子串长度或者回文子串个数的题目用马拉车算法解决就可以了,如果不熟悉马拉车算法的话,可以看看这个链接:
http://www.cnblogs.com/bitzhuwei/p/Longest-Palindromic-Substring-Part-II.html


解法(马拉车算法)

class Solution {
    public String longestPalindrome(String s) {
        if(s == null || s.length() == 0) return "";

        int len = 2 * s.length() + 3;
        int[] P = new int[len];
        char[] T = new char[len];

        T[0] = '!';
        T[1] = '#';
        int t = 2;
        for(char c : s.toCharArray()){
            T[t++] = c;
            T[t++] = '#';
        }
        T[t] = '$';
        //C为中心,R为右边界
        int C = 0,R = 0;

        for(int i = 1;i < len - 1;i++){
            //与i对称的i'
            int mirror = 2 * C - i;
            //与右边界的距离
            int diff = R - i;
            //若在右边界和中心内,否则更新中心和右边界
            if(diff >= 0){
                //若P[mirror] < diff,说明可以利用对称性质,否则更新中心和右边界
                if(P[mirror] < diff){
                    P[i] = P[mirror];
                }else{
                    P[i] = diff;
                    while(T[i + P[i] + 1] == T[i - P[i] - 1]) P[i]++;
                    C = i;
                    R = i + P[i];
                }
            }else{
                while(T[i + P[i] + 1] == T[i - P[i] - 1]) P[i]++;
                C = i;
                R = i + P[i];
            }
        }

       int maxLength = -1, center = -1;
       for(int i = 1;i < len - 1;i++){
            if(P[i] > maxLength){
                maxLength = P[i];
                center = i;
            }
        }

        return s.substring((center -1 - maxLength) / 2,(center - 1 - maxLength) / 2 + maxLength);
    }
}
阅读更多

没有更多推荐了,返回首页