簡體   English   中英

遞歸循環遍歷字符串中的字符以解決回文問題的問題

[英]Problem recursively looping through characters in a string to solve Palindrome problem

我試圖遞歸地解決一個通用的回文問題。 但是,我的算法似乎只評估第一個遞歸調用,而不是第二個,后者應該檢查字符串中的所有字符。 我的算法中顯然存在邏輯錯誤,但我無法發現它。 誰能建議? 請參閱下面的代碼。

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

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

    // Base Case: 
    if(totalChars === 0) return true;
    if (lowIdx === highIdx) return true;
    if (lowIdx > highIdx) {
        console.log(`Endpoint reached; STR: ${str}; LOW: ${str[lowIdx]}; high: ${str[highIdx]}`);
        return;
    }

    if(str[lowIdx] === str[highIdx]) {
        console.log(`Loop through idx; STR: ${str}; LOW: ${str[lowIdx]}; high: ${str[highIdx]}`);
        return true;
    }
    else if(str[lowIdx] !== str[highIdx]) return false;


    // Recursive Case:
    return isPalindrome(totalChars, highIdx, str) && 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"));

有幾個問題:

  1. 您的if...else將始終導致return ,因此永遠不會執行帶有遞歸調用的語句。

    請注意, else if之后的條件在被評估時將始終為真,因為它是在較早的if語句中評估的條件的否定。

    更重要的是,當前面的if條件為真時,您不想返回,因為尚未驗證剩余(內部)字符是否匹配。 這仍然需要通過遞歸調用來驗證,所以這不是執行return的地方。 只需刪除if塊,並且僅在字符不同時才return

    所以替換這個:

     if(str[lowIdx] === str[highIdx]) { return true; } else if(str[lowIdx];== str[highIdx]) return false;

    只有:

     if(str[lowIdx];== str[highIdx]) return false;
  2. 第一個遞歸調用傳遞與當前執行的 function相同的 arguments——這將導致無限遞歸。 遞歸調用必須始終使問題變小。 在這種情況下,實際上沒有必要進行兩次遞歸調用,您應該刪除第一個。

    所以替換這個:

     return isPalindrome(totalChars, highIdx, str) && isPalindrome(totalChars, highIdx-1, str);

    和:

     return isPalindrome(totalChars, highIdx-1, str);
  3. 基本情況有一個條件,即在沒有 boolean return值的情況下執行返回。 function 應始終返回 boolean 值。 在這種情況下,它應該是true ,因為這意味着所有字符對都進行了比較,並且沒有剩余的單個中間字符(字符串的大小是偶數)。 因此,您可以將此案例與之前的基本案例結合起來。 事實上,當totalChars為零時,該基本情況條件也適用,因此您可以先省略它if

    所以改變這個:

     if (totalChars === 0) return true; if (lowIdx === highIdx) return true; if (lowIdx > highIdx) { return; }

    和:

     if (lowIdx >= highIdx) return true;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM