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"

难度:Medium

题目是说, 给出一个字符串, 求出这个字符串的最长"回文"的子串. 回文是指前后完全对称的字符串, 像是abba cabac 之类的都算是回文.

奇数字母的回文和偶数字母的回文中心是不一样的, 奇数字母比如aba的中心在中间字母上, 偶数字母比如abba的回文在中间两字母的中心上, 由此可见, 回文中心点实际上最小间隔是"半个"字符. 我们可以考虑回文中心以半个字符间距不断移动, 去寻找最长回文子串.

public class Solution {
    public String longestPalindrome(String s) {
        int len = s.length();
        int maxl = 0;
        int maxr = 0;
        int maxLen = 1;
        for (int k = 0; k < len * 2 - 1; k++) {
            int base = 0;
            int plen = 1;
            int left = k / 2;
            int right = k / 2;
            if (k % 2 == 1) {
                base = 1;
                plen = 0;
                left = (k - 1) / 2;
                right = (k + 1) / 2;
            }
            for (int i = base; k - i >= 0 && (k + i) / 2 <= len - 1; i = i + 2) {
                int l = (k - i) / 2;
                int r = (k + i) / 2;
                if (s.charAt(l) != s.charAt(r)) {
                    break;
                }
                left = l;
                right = r;
                plen = r - l + 1;
            }
            if (plen > maxLen) {
                maxl = left;
                maxr = right;
                maxLen = plen;
            }
        }
        return s.substring(maxl, maxr + 1);
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.longestPalindrome("a"));
        System.out.println(s.longestPalindrome("aba"));
        System.out.println(s.longestPalindrome("aa"));
        System.out.println(s.longestPalindrome("abac"));
        System.out.println(s.longestPalindrome("baab"));
    }
}

EthanSun
45 声望3 粉丝