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