LeetCode-Longest Palindromic Substring

Description:
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”

题意:给定一个字符串,要求输出这个串的最长回文连续子串;

第一种解法:暴力求解是最简单的一个方法,但是我们可以从最大长度开始寻找最长的回文串,在遍历的过程中一旦找到一个是回文的子串,那么他就是最长的;

class Solution {
    public String longestPalindrome(String s) {
        for(int i=s.length(); i>1; i--){
            for(int j=0; j+i<=s.length(); j++){
                String str = s.substring(j, j+i);
                if(isPalindrome(str)){
                    return str;
                }
            }
        }
        //不存在长度为二及以上的回文串
        return s.substring(0, 1);
    }

    private boolean isPalindrome(String s){
        int st, ed;
        st = 0;
        ed = s.length() - 1;
        while(st < ed){
            if(s.charAt(st++) != s.charAt(ed--)){
                return false;
            }
        }
        return true;
    }//判断字符串是否为回文
}

第二种解法:回文串的一个特点就是中心向外扩散,从中间往两端,左右字符是相同的,对于长度为n的字符串,一共有2n-1个中心点,因为可能回文串中字符的个数是偶数个,这时的中心点在中间两个元素之间;根据这个特点,我们遍历所有的中心点,找出最长长度的回文串;

class Solution {
    public String longestPalindrome(String s) {
        int st, ed;
        st = ed = 0;
        for(int i=0; i<s.length(); i++){
            int len1 = getLongest(s, i, i);//元素坐标点
            int len2 = getLongest(s, i, i+1);//元素中间坐标点
            int len = len1 > len2 ? len1 : len2;
            if(len > ed - st){
                st = i - (len - 1) / 2;
                ed = i + len / 2;
            }
        }
        return s.substring(st, ed+1);
    }

    private int getLongest(String s, int left, int right){
        while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){
            left--;
            right++;
        }
        return right - left - 1;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/80942980