0%
Loading ...

【Leetcode 筆記】 125. Valid Palindrome

題目解釋

給定一個字串 s,如果它是回文 (palindrome) 則傳回 true,否則傳回 false。

需要統一 downcase 成小寫字母以及移除所有非字母的部分(數字、標點符號等)。

範例

  • 輸入: s = "A man, a plan, a canal: Panama"
  • 輸出: true

處理後的字串 "amanaplanacanalpanama" 是回文。

最佳解法

步驟

  1. s 處理後存為 cleaned_str
  2. 令雙指標 leftright
  3. 比較 leftright 指到的字母是否一樣

程式碼

class Solution:
    def isPalindrome(self, s: str) -> bool:
        cleaned_str = ""
        for i in s:
            if i.isalnum():
                cleaned_str += i.lower()

        left, right = 0, len(cleaned_str) - 1
        while left < right:
            if cleaned_str[left] != cleaned_str[right]:
                return False
            left += 1
            right -= 1
        return True

時間複雜度

O(n),n 是 s 的字母個數。

空間複雜度

O(n)

結語

個人感覺要記得 isalnum() 這件事可比用雙指標難多了。

數據女巫 𝔻.𝕡𝕪𝕤 🔮

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.