5. Longest Palindromic Substring

Posted feng-ying

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    }
}

 

以上是关于5. Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 5. Longest Palindromic Substring

5. Longest Palindromic Substring - Unsolved

5. Longest Palindromic Substring

5. Longest Palindromic Substring

[LeetCode] 5 Longest Palindromic Substring

5. Longest Palindromic Substring