首页 > 其他分享 >leetcode 5. 最长回文子串

leetcode 5. 最长回文子串

时间:2022-11-13 17:15:00浏览次数:74  
标签:子串 return string 示例 ans leetcode 回文

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

 

示例 1:

输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。

示例 2:

输入:s = "cbbd"
输出:"bb"

 

提示:

  • 1 <= s.length <= 1000
  • s 仅由数字和英文字母组成

原题链接

/**
 * @param {string} s
 * @return {string}
 */
// 动态规划实现
var longestPalindrome = function(s) {
    let l = s.length;
    if(l<=1){
        return s
    }
    let ans = "";
    let dp = new Array(l).fill(0).map(()=>new Array(l));
    for(let i=1;i<l;i++){
        for(let j=0;j<=i;j++){
            // 满足以下条件,即相比较的两个字符相等且他们是同一个字符或相邻的字符或他们那各自往回缩一个字符还是回文
            if(s.charAt(i)===s.charAt(j)&&(i-j<2||dp[j+1][i-1])){
                dp[j][i]=true;
                let res =  s.substring(j,i+1);
                ans=res.length>ans.length?res:ans;
            }
        }
    }
    return ans;
};

解法参考回文子串实现方案。

标签:子串,return,string,示例,ans,leetcode,回文
From: https://www.cnblogs.com/beileixinqing/p/16886304.html

相关文章

  • 剑指 Offer 41. 数据流中的中位数 - 力扣(Leetcode)
    剑指Offer41.数据流中的中位数-力扣(Leetcode)分析维护两个堆,一个大根堆,一个小根堆。插入操作:当进行插入时,先判断大根堆中是否有元素,如果没有直接插入大根堆,若有......
  • 剑指 Offer 59 - I. 滑动窗口的最大值 - 力扣(Leetcode)
    剑指Offer59-I.滑动窗口的最大值-力扣(Leetcode)一.分析方法一:数组长度为1e5,k的大小为1e4,因此直接暴力计算会TLE。我们可以思考一个更复杂的问题:询问任意区间中的......
  • [回溯算法]leetcode40. 组合总和 II(c实现)
    题目给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。candidates 中的每个数字在每个组合中......
  • leetcode 647. 回文子串 js实现
    给你一个字符串 s ,请你统计并返回这个字符串中 回文子串 的数目。回文字符串 是正着读和倒过来读一样的字符串。子字符串 是字符串中的由连续字符组成的一个序列。......
  • LeetCode 665. 非递减数列
    classSolution{public:boolcheckPossibility(vector<int>&nums){intn=nums.size();for(inti=0;i<n-1;i++){intx=nums[i......
  • LeetCode刷题记录.Day13
    四数之和18.四数之和-力扣(LeetCode)classSolution{public:vector<vector<int>>fourSum(vector<int>&nums,inttarget){vector<vector<int>>res......
  • #yyds干货盘点# LeetCode 腾讯精选练习 50 题:最小栈
    题目:设计一个支持push,pop,top操作,并能在常数时间内检索到最小元素的栈。实现MinStack类:MinStack()初始化堆栈对象。voidpush(intval)将元素val推入堆栈。voidpop......
  • leetcode-888-easy
    FairCandySwapAliceandBobhaveadifferenttotalnumberofcandies.YouaregiventwointegerarraysaliceSizesandbobSizeswherealiceSizes[i]isthenum......
  • leetcode-1486-easy
    XOROperationinanArrayYouaregivenanintegernandanintegerstart.Defineanarraynumswherenums[i]=start+2*i(0-indexed)andn==nums.length......
  • Leetcode第790题:多米诺和托米诺平铺(Domino and tromino tiling)
    解题思路采用动态规划思路。参考题解。核心代码如下:constlonglongmod=1e9+7;classSolution{public:intnumTilings(intn){vector<vector<lo......