簡體   English   中英

有人可以解釋這種回文解決方案嗎?

[英]Can someone please explain this Palindrome solution?

好的,因此我正在嘗試改進我的JS,並且遇到了流行的Palindrome Checker練習。 這次,來自freeCodeCamp的此解決方案應該表現得很好,但是我無法理解它的幾個方面。

/this solution performs at minimum 7x better, at maximum infinitely better.
    //read the explanation for the reason why. I just failed this in an interview.
    function palindrome(str) {
      //assign a front and a back pointer
      let front = 0
      let back = str.length - 1

      //back and front pointers won't always meet in the middle, so use (back > front)
      while (back > front) {
        //increments front pointer if current character doesn't meet criteria
        if ( str[front].match(/[\W_]/) ) {
          front++
          continue
        }
        //decrements back pointer if current character doesn't meet criteria
        if ( str[back].match(/[\W_]/) ) {
          back--
          continue
        }
        //finally does the comparison on the current character
        if ( str[front].toLowerCase() !== str[back].toLowerCase() ) return false
        front++
        back--
      }

      //if the whole string has been compared without returning false, it's a palindrome!
      return true

    }

現在,我對此代碼有幾個疑問:

1-將str的長度減少1的意義是什么? 我已經在多個回文檢查器中看到了這一點,但仍然無法繞開它。

2- .match方法是否意味着“如果參數包含這些字符,則返回true”?

3-為什么“ / [\\ W _] /”等於“所有字符”?

4-在前后加1減1的意義是什么? 特別是在功能結束時。

謝謝,很抱歉,如果這是一個愚蠢的問題,我真的很想理解這里的邏輯。

為了回答您的第一個問題,“ back”是一個指向字符串后面的指針。 其值為str.length - 1的原因是,盡管索引從0開始,但str.length將給出字符串中屬性的數量。因此,您需要從長度中減去1才能獲得索引最后一個屬性。

要回答您的最后一個問題,分別在前面/后面加1 /減去1是為了使要測試的屬性彼此相對。 例如,如果字符串是“ abba”,則在比較第一個字母和最后一個字母之后,它將增加計數器,以便將第一個b(新的“ front”)與第二個b(新的“ back”)進行比較。 ')

同時查看字符串的前端和字符串的末端並進行比較。 在每個循環中,它將從前進和后退向后移動:

loop 1
  amanaplanacanalpanama
  |                   |
front                back

front === back? if not it iss not a palindrome

loop 2 (front+1 & back -1)
  amanaplanacanalpanama
   |                 |
 front              back

front === back?

etc.

如果繼續返回true,則說明您有回文。

您可能會遇到的問題是回文,例如:

夫人,我是亞當

'和空格將其弄亂了,但大多數人仍將其稱為回文。 這就是為什么你有這樣的行:

str[back].match(/[\W_]/)

.match(/[\\W_]/)測試一個字母是否為“'單詞”之類的“非單詞”字母,甚至是一個空格,然后將前指針向后移動到指針上方。 這使測試不必關心空格和非單詞字符。

暫無
暫無

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

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