leetcode5 最长回文子串

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

示例 1:
复制代码
输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。
示例 2:
复制代码
输入:s = "cbbd"
输出:"bb"
思路

以当前字符为中心点,向两边扩展

以当前字符和下一个字符为中心(即回文串长度为偶数)

更新最长回文子串的起始和结束位置

java 复制代码
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 + 1) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }
    private int expandAroundCenter(String s, int left, int right) {
        int L = left, R = right;
        while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
            L--;
            R++;
        }
        return R - L - 1;
    }
}
相关推荐
热爱Java,热爱生活1 天前
浅谈Spring三级缓存
java·spring·缓存
ConardLi1 天前
把 Claude Design 做成 Skill,你的网站也能拥有顶级视觉体验
前端·人工智能·后端
@ chen1 天前
IDEA初始化配置
java·ide·intellij-idea
We་ct1 天前
LeetCode 120. 三角形最小路径和:动态规划详解
前端·javascript·算法·leetcode·typescript·动态规划
liuyunshengsir1 天前
linux 下新增用户后无法使用TAB补全功能的最佳解决方法
linux·运维·服务器
wellc1 天前
SpringBoot集成Flowable
java·spring boot·后端
IT_陈寒1 天前
React状态更新那点事儿,我掉坑里爬了半天
前端·人工智能·后端
cwxcc1 天前
Google Core Web Vitals(核心网页指标)
前端·性能优化
|晴 天|1 天前
Vue 3 + LocalStorage 实现博客游戏化系统:成就墙、每日签到、积分商城
前端·vue.js·游戏
Hui Baby1 天前
springAi+MCP三种
java