2023-11-28|閱讀時間 ‧ 約 4 分鐘

[Leetcode] 125. Valid Palindrome

題目 : 125. Valid Palindrome

  • A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
  • Given a string s, return true if it is a palindrome, or false otherwise.


Example 1:

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.

Example 2:

Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.

Example 3:

Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.


1.

front : 從index=0開始數的索引值

back : 字串的最尾端往前數的索引值

isalnum() : 用來判斷該字串/字元是否由數字和字母所組成

lower() : 將字串/字元轉成小寫字母


用front和back這2個索引值一一查看該字串是否回文

如果要比對的字元不是數字或字母 -> 索引值+1/-1

用lower()將字母轉成小寫,如果s[front]s[back]不一樣,回傳 False

全部比對完回傳 True

class Solution:
def isPalindrome(self, s: str) -> bool:

front, back = 0, len(s)-1

while(front<back):
while front<back and not s[front].isalnum():
front +=1

while front<back and not s[back].isalnum():
back -=1

if s[front].lower() != s[back].lower():
return False
front += 1
back -= 1

return True





分享至
成為作者繼續創作的動力吧!
這裡會放一些我寫過的 Leetcode 解題,目前的筆記都是使用python做解題
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

Youna's Devlog 的其他內容

發表回應

成為會員 後即可發表留言
© 2024 vocus All rights reserved.