Leetcode热题100(Leetcode_5)-最长回文子串

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

示例 1:

输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:

输入: "cbbd"
输出: "bb"

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring
 

我个人认为这样的题目并不难,但是今晚不知道是状态不好还是为啥,硬是看了半天没想出好的解决方案,现在冷静下来以看,只要采用中心扩展算法即可解决问题。(虽然我是看了Leetcode题解才做出来的),下面贴代码吧,就当记录一下了

public String longestPalindrome(String s) {
    if(s==null||s.length()==0)
        return "";
    int index = 0;
    int a = 0;
    int b = 0;
    int maxLen = 0;
    while (index<s.length()){
        int[] ab = judge(s,index);
        int[] ab2 = judge2(s,index);
        if((ab[1]-ab[0]+1)>(ab2[1]-ab2[0]+1)) {
            if ((ab[1] - ab[0] + 1) > maxLen) {
                maxLen = ab[1] - ab[0] + 1;
                a = ab[0];
                b = ab[1];
            }
        }else {
            if ((ab2[1] - ab2[0] + 1) > maxLen) {
                maxLen = ab2[1] - ab2[0] + 1;
                a = ab2[0];
                b = ab2[1];
            }
        }
        index++;
    }
    return s.substring(a,b+1);
}

private int[] judge(String s,int index){
    int a = index;
    int b = index;
    int[] result = new int[2];
    while (a>=0&&b<s.length()){
        if(s.charAt(a)!=s.charAt(b)){
            break;
        }
        a--;
        b++;
    }
    result[0] = a+1;
    result[1] = b-1;
    return result;
}

private int[] judge2(String s,int index){
    int a = index;
    int b = index+1;
    int[] result = new int[2];
    while (a>=0&&b<s.length()){
        if(s.charAt(a)!=s.charAt(b)){
            break;
        }
        a--;
        b++;
    }
    result[0] = a+1;
    result[1] = b-1;
    return result;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值