[Leetcode] 125. Valid Palindrome

閱讀時間約 3 分鐘

題目 : 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





7會員
47內容數
這裡會放一些我寫過的 Leetcode 解題和學習新技術的筆記
留言0
查看全部
發表第一個留言支持創作者!
Youna's Devlog 的其他內容
[Leetcode] 242. Valid Anagram
閱讀時間約 3 分鐘
[Leetcode] 217. Contains Duplicate
閱讀時間約 2 分鐘
[Leetcode] 1. Two Sum
閱讀時間約 1 分鐘
[Leetcode] 49. Group Anagrams
閱讀時間約 3 分鐘
你可能也想看
【LeetCode】19.Remove Nth Node From End of ListInput: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]
Thumbnail
avatar
2021-10-09
【LeetCode】876. Middle of the Linked ListInput: head = [1,2,3,4,5] Output: [3,4,5] 單看列表只是要找中間值,不過給定的資料結構不是陣列,而是鏈結串列。
Thumbnail
avatar
2021-10-09
【LeetCode】189. Rotate Array之前跳過的題目,回來補完成。 Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4]
Thumbnail
avatar
2021-10-08
【LeetCode】557. Reverse Words in a String III今日題目: 把一行字內每個單字都反轉字元。 Input: s = "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Thumbnail
avatar
2021-10-08
【LeetCode】344. Reverse String今日題目:字串反轉 Input: s = ["h","e","l","l","o"] Output: ["o","l","l","e","h"]
Thumbnail
avatar
2021-10-08
【LeetCode】167. Two Sum II 題目如下: Input: numbers = [2,7,11,15], target = 9 Output: [1,2]
Thumbnail
avatar
2021-10-07
【LeetCode】283. Move Zeroes題目要求如下: Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] 把0都搬到後面去,非0的數字移到前面,且不更改原本數字的大小順序。
Thumbnail
avatar
2021-10-07
【LeetCode】977. Squares of a Sorted Array比今天的題目示例如下: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] 簡單來說,要的輸出結果是把陣列內每個數字取平方後,對陣列做排序。
Thumbnail
avatar
2021-10-06
【LeetCode】704. Binary SearchLeetcode上正好有14天的讀書計畫,今天三題都是二分搜索,順手三題都寫一寫,想法上很固定。
Thumbnail
avatar
2021-10-05
【LeetCode】20. Valid Parentheses 前幾天看別人直播刷題,心血來潮打開很久沒動的leetcode試試,挑了一題當初面試沒寫出來的題目。嗯...我那時才剛碰資料結構,知道要用stack寫卻沒實作過任何東西,現在有工作經驗後再來寫,看看會不會有不一樣的想法。
Thumbnail
avatar
2021-10-04