You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

递归遍历字符串实现回文判断的逻辑错误排查求助

递归回文判断的问题修复

核心问题分析

你的代码里递归逻辑永远不会被执行,因为在递归调用代码之前,已经通过if/else if直接返回了true或false,程序根本走不到递归分支。另外还有几个边界条件和递归参数的错误:

  1. 提前返回阻断递归:当首尾字符相等时直接return true,没有继续递归检查内部子串;不等时直接return false,完全跳过递归逻辑。
  2. 递归参数错误:第一个递归调用传入的highIdx和当前值一致,会造成无限递归;正确做法是缩小检查范围,把highIdx-1作为新的右边界,无需同时调用两个递归(这是逻辑误解,回文只需逐步向中间收缩检查)。
  3. 边界条件返回值错误:lowIdx > highIdx时应返回true(所有字符已匹配完成),而非undefined,否则会导致布尔运算结果异常。

修复后的代码

function isPalindrome(totalChars: number, lastIdx: number, str: string): boolean {
    console.log(`lastIdx: ${lastIdx}; char: ${str[lastIdx]}`);

    let highIdx = lastIdx;
    const lowIdx = totalChars - 1 - highIdx;

    // 边界条件修正
    if (totalChars === 0) return true;
    if (lowIdx >= highIdx) return true; // 合并中间点和超出边界的情况,统一返回true

    // 字符不相等直接返回false
    if (str[lowIdx] !== str[highIdx]) {
        console.log(`Mismatch at idx; STR: ${str}; LOW: ${str[lowIdx]}; high: ${str[highIdx]}`);
        return false;
    }

    // 递归收缩右边界,继续检查内部子串
    console.log(`Continue checking inner substring; STR: ${str}; LOW: ${str[lowIdx]}; high: ${str[highIdx]}`);
    return isPalindrome(totalChars, highIdx - 1, str);
}

// 测试用例
console.log("a is Palindrome: " + isPalindrome("a".length, "a".length-1, "a"));
console.log("motor is Palindrome: " + isPalindrome("motor".length, "motor".length-1,"motor"));
console.log("rotor is Palindrome: " + isPalindrome("rotor".length, "rotor".length-1,"rotor"));

修复说明

  • 移除提前返回true的逻辑,仅当字符不匹配时直接返回false,否则进入递归收缩边界。
  • 合并lowIdx === highIdx和lowIdx > highIdx的边界条件,统一返回true,简化逻辑。
  • 递归调用仅传递highIdx-1,每次检查完首尾字符后,只需检查去掉首尾的内部子串,避免原代码的双递归逻辑错误。
  • 确保所有分支返回布尔值,避免undefined导致的结果异常。

更简洁的优化(可选)

totalChars参数属于冗余项,可直接用str.length代替,简化函数参数:

function isPalindrome(str: string, left: number = 0, right: number = str.length - 1): boolean {
    if (left >= right) return true;
    if (str[left] !== str[right]) return false;
    return isPalindrome(str, left + 1, right - 1);
}

console.log("a is Palindrome: " + isPalindrome("a"));
console.log("motor is Palindrome: " + isPalindrome("motor"));
console.log("rotor is Palindrome: " + isPalindrome("rotor"));

这个版本通过左右指针向中间收缩,更符合递归回文判断的常规写法,逻辑更清晰。

内容的提问来源于stack exchange,提问作者tlockhart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:05:22