iT邦幫忙

2022 iThome 鐵人賽

DAY 9
0
自我挑戰組

30天 Neetcode解題之路系列 第 9

Day 9 - 125. Valid Palindrome

  • 分享至 

  • xImage
  •  

前言

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
來到Two Pointers的部分~
前面Array & Hashing有一題破不了,Encode and Decode Strings要訂閱才能寫QQ,於是Pass~XD

那就開始今天的解題吧~


Question

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.

Constraints:

  • 1 <= s.length <= 2 * 10^5
  • s consists only of printable ASCII characters.

Think

簡單的說,就是要判斷字串是不是回文的格式。

只是這題的測資有很多特殊符號需要移除掉QQ,測了好多次才找到全部的符號...

Code

class Solution:
    def isPalindrome(self, s: str) -> bool:
        s = s.strip()
        for character in ['\\', '`', '*', '_', '{',\
                          '}', '[', ']', '(', ')', \
                          '>', '#', '+', '-', '.', 
                          '!', '$', '\'', ' ', ',',\
                          ':', '%', '^', '<', '&',\
                          '=', '?', '{', '}', '|',\
                          '/', '~', '@', '\"', ';']:
            if character in s:
                s = s.replace(character,"")
        s = s.lower()
        # print(s)
        
        low = 0
        high = len(s)-1
        
        while(low<=high):
            if s[low] != s[high]:
                return False
            low += 1
            high -= 1
        
        return True

Submission


今天就到這邊啦~
大家明天見/images/emoticon/emoticon29.gif


上一篇
Day 8 - 128. Longest Consecutive Sequence
下一篇
Day 10 - 167. Two Sum II - Input Array Is Sorted
系列文
30天 Neetcode解題之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言