打卡-最长回文子串

1. 题目描述

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

2. 示例

在这里插入图片描述

3. 提示
  1. 1 <= s.length <= 1000
  2. s 仅由数字和英文字母组成(大小写)
4. solution
  1. 最外层循环从索引为1 到 最大索引;
  2. 从索引为1开始查找,若左右元素相同,再继续向两侧扩展(但只考虑这种情况不适用于类似 aaaa 的例子),求得一个最大长度;
  3. 为了处理上述情况(以 aaaa 为例),添加了下面的代码,从索引为2开始,若与左侧相等,则从索引 1 与 2 同时往两侧扩展(但只考虑这种情况不适用于处理类似 aaa 的例子),求得一个最大长度。
  4. 取两种情况的最大长度,并记录下索引位置。
  5. 根据记录的索引位置输出即可。
class Solution {
    public String longestPalindrome(String s) {
        // 1.特殊情况:长度为一的字符串,直接返回
        if(s.length() == 1){
            return s;
        }
        // 2.一般情况:循环查找
        int max = 1,start = 0,end = 0;
        char[] cStr = s.toCharArray();// 转化为字符数组
        for (int i = 1; i < cStr.length; i++) {
            int left = i, right = i, count = 1;// 存放当前最大回文子串的始末索引,及长度
            while ((left - 1) >= 0 && (right + 1) < cStr.length) {
                if (cStr[left - 1] == cStr[right + 1]) {
                    left -= 1;
                    right += 1;
                    count += 2;
                } else {
                    break;
                }
            }
            if(max < count){
                start = left;
                end = right;
                max = count;
            }

            left = i;right = i;count = 1;// 存放当前最大回文子串的始末索引,及长度
            if((left-1)>=0 && (cStr[left]==cStr[left-1])){
                left -= 1;
                ++count;
            }
            while((left-1)>=0 && (right+1)<cStr.length){
                if(cStr[left-1] == cStr[right+1]){
                    left -= 1;
                    right += 1;
                    count += 2;
                }else{
                    break;
                }
            }
            if(max < count){
                start = left;
                end = right;
                max = count;
            }
        }
        // 3.输出索引为 left ~ right 之间的字符组成的字符串
        String result = "";
        for (int i = start; i <= end; i++) {
            result += cStr[i];
        }
        return result;
    }
}
5. 题目来源

力扣

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值