leetcode - palindromic longest substring

topic:

Given a string s, s to find the longest substring palindromic. You can assume that the maximum length of 1000 s.

Example 1:

输入: "babad"
输出: "bab"

Note: "aba" is a valid answer.

Example 2:

输入: "cbbd"
输出: "bb"

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/longest-palindromic-substring
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.


class Solution {
    public String longestPalindrome(String s) {
        // 中心扩散法:如字符串s长度为n,则共有n+(n-1)== 2n-1个中心点,计算出以每个点为中心的最长回文子串,记录起始位置i和终止位置j
        if(s.length() == 0)
            return "";
        int left = 0, right = 0;
        for (int i = 0; i < s.length(); i++) {
            int odd = maxLength(s, i, i);  // // 以i为中心点
            int even = maxLength(s, i, i + 1);  // 以i和i+1之间为中心点
            int m = Math.max(odd, even);
            if (m > right - left) {
                left = i - (m - 1) / 2;  // 确定当前最大回文子串的起始点位置
                right = i + m / 2;  // 确定当前最大回文子串的结束点位置
            }
        }
        return s.substring(left, right+1);
    }
    
    // 计算最大回文字串长度
    public int maxLength(String s, int left, int right){
        while(left>=0 && right<s.length() && s.charAt(left) == s.charAt(right)){
            left--;
            right++;
        }
        return right-left-1;
    }
}

Guess you like

Origin www.cnblogs.com/paopaolx/p/11359682.html