欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > 【Hot100】LeetCode—5. 最长回文子串

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

2025/2/26 19:00:05 来源:https://blog.csdn.net/weixin_44382896/article/details/142173734  浏览:    关键词:【Hot100】LeetCode—5. 最长回文子串

目录

  • 1- 思路
    • 题目识别
    • 动规五部曲
  • 2- 实现
    • 5. 最长回文子串——题解思路
  • 3- ACM 实现


  • 原题链接:5. 最长回文子串

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. 最长回文子串——题解思路

在这里插入图片描述

class Solution {public String longestPalindrome(String s) {// 1. 利用回文子串求解// 定义 dpint len = s.length();boolean[][] dp = new boolean[len][len];// 2. 递推公式// 只有相等的时候 需要进行递推// 3. 初始化// 默认都是 falseString 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 实现

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));}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词