使用递归计算回文数 [英] Counting Palindromes using recursion

查看:59
本文介绍了使用递归计算回文数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个代码,可以计算给定字符串中的回文数,并且在我用"appal"测试该字符串之前一直运行良好.该函数在应返回2(appa和pp)时返回0,如果有人可以编辑当前代码以使其符合要求,我将不胜感激,谢谢!这是我的代码:

I currently have a code which counts the palindromes in a given string and it was working fine till I tested it with "appal" the function returned 0 when it should return 2 (appa and pp) I would really appreciate it if someone can edit my current code so that it meets that requirement, thank you! Here's my code:

function countPalindromes(string, count) {
  if (string.length <= 1) {
    return count;
  }

  let [ firstLetter ] = string;
  let lastLetter = string[string.length - 1];

  if (firstLetter === lastLetter) {
    let stringWithoutFirstAndLastLetters = string.substring(1, string.length - 1);
    return countPalindromes(stringWithoutFirstAndLastLetters, count + 1);
  } else {
    return 0;
  }
}

console.log(countPalindromes("kayak", 0));
console.log(countPalindromes("aya", 0));
console.log(countPalindromes("appal", 0));

推荐答案

我认为此功能可以解决问题.很高兴在以后进行重构和解释.我宁愿编写一个新函数,因为我认为您的代码不接近执行任务.

I think this function does the trick. Happy to refactor and explain it later. I'd rather write a new function because I don't think your code is close to executing the task.

function returnNumberOfPalindromes(word) {
    function isPalindrome(chunk) { 
        return [...chunk].reverse().join('') === chunk;
    }
    let tally = 0;
  
    for (let index1 = 0; index1 <= word.length; index1++) {
      for (index2 = index1 + 2; index2 <= word.length; index2++) { 
        let chunk = word.slice(index1, index2); 
        if (isPalindrome(chunk)) {
            tally += 1;
        };
      }
    }
    console.log(tally);
}

returnNumberOfPalindromes("kayak");
returnNumberOfPalindromes("aya");
returnNumberOfPalindromes("appal");
returnNumberOfPalindromes("addadaadd");

这篇关于使用递归计算回文数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆