5. 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"

解答:从字符串的第一个元素开始遍历回文串,最短的回文串长度为1,每次只记录最长的回文串。

java实现:

public class LongestPalindromicSubstring {
    private static int left = 0, length = 0;
    public static String longestPalindrome(String s) {
        for(int i = 0; i < s.length(); i++){
            expandAroundCenter(s, i);
        }
        return s.substring(left, left + length);
    }

    private static void expandAroundCenter(String s, int start){
        int end = start + 1;
        start = start - 1;
        // 巧妙的地方在于如果遇到重复的元素,那么这些重复的元素一定可以作为回文串的中心字符,不需要考虑奇数还是偶数。
        while(end < s.length() && (s.charAt(end) == s.charAt(end - 1))) end++;
        while(start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)){
            start--;
            end++;
        }
        if(end - start -1 > length){
            left = start + 1;
            length = end - start -1;
        }
    }

    public static void main(String[] args){
        String s = "jfkdslibbasdffdsabbcdfsdkfj";
        String result = longestPalindrome(s);
        System.out.println(result);
    }
}
原文地址:https://www.cnblogs.com/feng-ying/p/10504597.html