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

leetcode 最长回文子串

时间:2022-10-20 09:59:28浏览次数:55  
标签:子串 const let Array strLen leetcode 回文

const countSubstrings = (s) => {
  const strLen = s.length;
  let numOfPalindromicStr = 0;
  // 初始化一个二维数组
  let dp = Array.from(Array(strLen), () => Array(strLen).fill(false));

  //对于动态规划问题,首先要看清两层for循环的结构,看看遍历的是哪些区域,哪些内容
  for (let j = 0; j < strLen; j++) {
    for (let i = 0; i <= j; i++) {
      // 外层的if是个分支结构,因为这个默认都是false,所以else的情况就是不用写
      if (s[i] === s[j]) {
        // 内层的if也是分支结构,主要用来将两种情况进行分流,对两种情况进行不同的逻辑处理
        if (j - i < 2) {
          dp[i][j] = true;
        } else {
          dp[i][j] = dp[i + 1][j - 1];
        }
        // 对回文子串的个数进行计数 
        numOfPalindromicStr += dp[i][j] ? 1 : 0;
        console.log(dp);
      }
    }
  }

  return numOfPalindromicStr;
};

const res = countSubstrings("cabac");
console.log(res);

标签:子串,const,let,Array,strLen,leetcode,回文
From: https://www.cnblogs.com/zhuoss/p/16808666.html

相关文章

  • 力扣leetcode 第2394题 求工作时间不达标的员工
    力扣leetcode第2394题求工作时间不达标的员工selectemployee_idfrom(selectDISTINCTe.employee_id,e.needed_hours*60asneeded_hours,ifnull((selectsum(......
  • 【算法训练营day7】LeetCode454. 四数相加II LeetCode383. 赎金信 LeetCode15. 三数之
    【算法训练营day7】LeetCode454.四数相加IILeetCode383.赎金信LeetCode15.三数之和LeetCode18.四数之和LeetCode454.四数相加II题目链接:454.四数相加II初次尝......
  • leetcode-101-easy
    SymmetricTree思路一:递归publicbooleanisSymmetric(TreeNodeleft,TreeNoderight){if(left==null&&right==null)returntrue;if(left==null......
  • leetcode-136-easy
    SingleNumber思路一:用set过滤,剩下唯一一个就是目标数字publicintsingleNumber(int[]nums){Set<Integer>set=newHashSet<>();for(intnum:num......
  • leetcode-202-easy
    HappyNumber思路一:happynumber的结果完全分类,就两种情况最后的值为1进入循环(用map记录)publicbooleanisHappy(intn){Set<Integer>set=newHash......
  • leetcode-141-easy
    LinkedListCycle思路一:用set记录每个节点的hashCode,如果遇到重复,说明是循环publicbooleanhasCycle(ListNodehead){Set<Integer>set=newHashSet<>();......
  • leetcode-344-easy
    ReverseString思路一:首尾互换publicvoidreverseString(char[]s){intmid=s.length/2;intbegin=0;intend=s.length-1;while(beg......
  • leetcode-263-easy
    UglyNumber思路一:从数字中依次去除2,3,5,查看剩余的值是否为1publicbooleanisUgly(intn){if(n==0)returnfalse;while(n%2==0){n/......
  • leetcode-217-easy
    ContainsDuplicate思路一:Set检测publicstaticbooleancontainsDuplicate(int[]nums){Set<Integer>set=newHashSet<>();for(intnum:nums){......
  • leetcode-709-easy
    ToLowerCase思路一:遍历,遇到A-Z范围内的char转换到对应a-z范围publicStringtoLowerCase(Strings){if(s==null||s.isEmpty())returns;int......