Palindrome - 5. Longest Palindromic Substring

6
  1. Longest Palindromic Substring

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

思路:

找出字符串中的回文字符串,解法有很多,比如dp,这里采用中容易想到的中心扩散法。主要区分一下偶回文和奇回文的处理,时间复杂度O(n^2),空间复杂度O(1)

代码:

java:

class Solution {

    public String longestPalindrome(String s) {

        if (s == null || s.length() == 0) return "";
        
        int start = 0, end = 0;
        for (int i = 0; i < s.length(); i++) {
            int len1 = expandAroundCenter(s, i, i); //奇回文  例如 cbabd
            int len2 = expandAroundCenter(s, i, i+1);   // 偶回文
            int len = Math.max(len1, len2);
            if (len > end- start) {
                start = i - (len -1) /2;
                end = i + len/2;
            }
        }

        return s.substring(start, end+1);
    }
    
    private int expandAroundCenter(String s, int left, int right) {
        int l = left, r = right;
        while(l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)){
            l--;
            r++;
        }
        
        return r - l - 1;
    }
}