java用递归求回文数,如何使用递归计算字符串中的所有回文?

I have a recursive function that checks if a string is a palindrome, but my assignment asks me to count the number of palindromes in a string (for example kayak has 2).

I'm really confused about how I can implement a recursive function that counts the number of palindromes. Here's my current code:

function isPalindrome(string) {

if (string.length <= 1) {

return true;

}

let [ firstLetter ] = string;

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

if (firstLetter === lastLetter) {

let stringWithoutFirstAndLastLetters = string.substring(1, string.length - 1);

return isPalindrome(stringWithoutFirstAndLastLetters);

} else {

return false;

}

}

解决方案

I think the accepted answer does not actually work. It will not count palindromes unless they are centered in the string and will count substrings that are not palindromes if as long as they start and end with the same letter. The answer from CertainPerformance would probably work but I think it would result in checking a lot of strings that don't need to be checked. Here's what I came up with, I think it works for the extra tests I've added.

function countPalindromes(string) {

if (string.length <= 1) {

return 0;

}

count = 0

for ( var i = 0; i < string.length; i++ ) {

count += countPalindromesCenteredAt(string, i)

count += countPalindromesCenteredAfter(string, i)

}

return count

}

function countPalindromesCenteredAt(string, i) {

count = 0

for ( var j = 1; i-j>=0 && i+j < string.length; j++ ) {

if (string.charAt(i-j) === string.charAt(i+j)) {

count += 1

}

else {

return count

}

}

return count

}

function countPalindromesCenteredAfter(string, i) {

count = 0

for ( var j = 1; i-j>=0 && i+j < string.length; j++ ) {

if (string.charAt(i-j+1) === string.charAt(i+j)) {

count += 1

}

else {

return count

}

}

return count

}

console.log(countPalindromes("kayak"));

console.log(countPalindromes("aya"));

console.log(countPalindromes("kayakcanoe"));

console.log(countPalindromes("kcanoek"));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值