0
点赞
收藏
分享

微信扫一扫

leetcode字符串5最长回文子串

witmy 2022-02-02 阅读 109

给你一个字符串 s,找到 s 中最长的回文子串。

示例 1:

输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。
示例 2:

输入:s = "cbbd"
输出:"bb"
示例 3:

输入:s = "a"
输出:"a"
示例 4:

输入:s = "ac"
输出:"a"

思路:

遍历字符串,对每个位置进行一次判定(在其位置的最大回文子串)

注意:回文子串不是指非得从中间开始的,例如ccccbbaabb,最大回文子串为bbaabb,因此需要从每个位置都要遍历

class Solution {
    public String longestPalindrome(String s) {
        //字符串的length有括号
        int length = s.length();
        //特殊情况,长度为0或者1时,直接返回
        if(length < 2){
            return s;
        }
        //start和end用来存储最大的区间
        int start = 0;
        int end = 0;
        int maxlength = 0;
        char[] chars = s.toCharArray();
        for(int i = 0; i < length; i++){
            //如果回文子串长度为奇数的情况
            int oddlength = ispalindrome(chars,i,i);
            //如果回文子串长度为偶数的情况
            int evenlength = ispalindrome(chars,i,i+1);
            int templength = Math.max(oddlength,evenlength);
            //如果有更大的回文子串长度,更新区间
            if(templength > end-start){
                start = i - (templength-1)/2;
                end = i + templength/2;
            }
        }
        return s.substring(start,end+1);
    }

    //判定是否为回文子串
    public int ispalindrome(char[] chars, int left, int right){
        //数组的长度没有括号
        int length = chars.length;
        while(left >= 0 && right < length && chars[left] == chars[right]){
            left--;
            right++;
        }
        return right-left-1;
    }
}
举报

相关推荐

0 条评论