Lcode算法30:最长回文子串

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

示例 1:

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

示例 2:

输入:s = "cbbd"
输出:"bb"
class Solution {
    public String longestPalindrome(String s) {
        if(s.length()<=1){
            return s;
        }
        int max = 0;
        String result = "";
        int count = 0;
        int bound = 0;
        for(int index =0;index<s.length();index++){
            count = rightIndex(s,index,index);
            if(count>=max && (index-(count-1)/2)<(index+(count-1)/2 + 1)){
                max = count;
                result = s.substring(index-(count-1)/2,index+(count-1)/2 + 1);
            }
            count = rightIndex(s,index,index+1);
            if(count>=max && (index-(count)/2+1)<(index+(count)/2 + 1)){
               max = count;
               result = s.substring(index-(count)/2+1,index+(count)/2 + 1);
            }
        }
        return result;
    }




    /**
        0 1 2 3 4 5
    */
    public int rightIndex(String s,int left,int right){
        int len = s.length();
        while(left>=0 && right<len && (s.charAt(left) == s.charAt(right)) ){
            left--;
            right++;
        }
        return right-left-1;
    }

   
}

官方相同解法:

class Solution {
    public String longestPalindrome(String s) {
        if (s == null || s.length() < 1) {
            return "";
        }
        int start = 0, end = 0;
        for (int i = 0; i < s.length(); i++) {
            int len1 = expandAroundCenter(s, i, i);
            int len2 = expandAroundCenter(s, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }

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

作者:力扣官方题解
链接:https://leetcode.cn/problems/longest-palindromic-substring/solutions/255195/zui-chang-hui-wen-zi-chuan-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值