leetcode字符串5最长回文子串

给你一个字符串 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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值