【Hot100】LeetCode—5. 最长回文子串

目录

  • [1- 思路](#1- 思路)
  • [2- 实现](#2- 实现)
    • [⭐++5. 最长回文子串++------题解思路](#⭐5. 最长回文子串——题解思路)
  • [3- ACM 实现](#3- ACM 实现)


1- 思路

题目识别

  • 识别1 :给一个 String 返回最长回文子串

动规五部曲

  • 1- 定义 dp 数组
    • dp[i][j] 代表 区间 [i,j] 是否为回文子串,如果是则为 true
  • 2- 递推公式
    • 只有在 s[i] == s[j] 的情况下,才需要进行递推。分三种情况
      • i == j :若是同一个元素,则 dp[i][j] 肯定为 true
      • ij 相差 1:若是两个相邻元素,则 dp[i][j] 也一定为 true
      • j - i > 1:若是相差两个以上的元素,需要判断 dp[i+1][j-1] 是否为 true
  • 3- 初始化
    • 默认所有 都是为 false
  • 4- 遍历顺序
    • dp[i][j]dp[i+1][j-1] 推导而来,也就是由左下角推导而来,因此
    • i 需要从 s.size() 来遍历

2- 实现

⭐++5. 最长回文子串++------题解思路

java 复制代码
class Solution {
    public String longestPalindrome(String s) {
        // 1. 利用回文子串求解
        // 定义 dp
        int len = s.length();
        boolean[][] dp = new boolean[len][len];

        // 2. 递推公式
        // 只有相等的时候 需要进行递推

        // 3. 初始化
        // 默认都是 false
        String res = "";
        // 4.遍历顺序
        for(int i = len-1;i>=0;i--){
            for(int j = i ; j < len;j++){
                if(s.charAt(i) == s.charAt(j)){
                    if( j - i <= 1 ){
                        dp[i][j] = true;
                    }else if(dp[i+1][j-1]){
                        dp[i][j] = true;
                    }
                    if(dp[i][j] && res.length() < j-i+1){
                        res = s.substring(i,j+1);
                    }
                }
            }
        }
        return res;
    }
}

3- ACM 实现

java 复制代码
public class longestPlainDrome {


    public static String longestP(String s){
        String res = "";
        // 1.定义 dp 数组
        int len = s.length();
        boolean[][] dp = new boolean[len][len];

        // 2.递推公式
        // 相等: <=1 则为 true ,否则得看 dp[i+1][j-1] 为 true 才为 true

        // 3. 初始化
        for(int i = len-1 ; i >= 0;i--){
            for(int j = i ; j < len;j++){
                if(s.charAt(i) == s.charAt(j)){
                    if( j - i <= 1){
                        dp[i][j] = true;
                    }else if(dp[i+1][j-1]){
                        dp[i][j] = true;
                    }
                    if(dp[i][j] && j-i+1 > res.length()){
                        res = s.substring(i,j+1);
                    }
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println("输入字符串");
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        System.out.println("结果是"+longestP(input));
    }
}
相关推荐
啃啃大瓜几秒前
python常量变量运算符
开发语言·python·算法
熊文豪8 分钟前
【华为OD】找出通过车辆最多颜色
算法·华为od
塔中妖13 分钟前
【华为OD】环中最长子串2
算法·华为od
JCBP_33 分钟前
QT(3)
开发语言·汇编·c++·qt·算法
研梦非凡43 分钟前
ICCV 2025|基于曲线感知高斯溅射的3D参数曲线重建
人工智能·算法·3d
XFF不秃头44 分钟前
力扣刷题笔记-三数之和
c++·笔记·算法·leetcode
一碗白开水一1 小时前
【第19话:定位建图】SLAM点云配准之3D-3D ICP(Iterative Closest Point)方法详解
人工智能·算法
编码浪子1 小时前
趣味学RUST基础篇(函数式编程闭包)
开发语言·算法·rust
Want5952 小时前
C/C++圣诞树②
c语言·c++·算法
索迪迈科技3 小时前
算法题(203):矩阵最小路径和
线性代数·算法·矩阵