2023年5月8日 星期一

5/9 每日一題

 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 * 105
  • s consists only of printable ASCII characters.


    class Solution:
        def isPalindrome(self, s: str) -> bool:
            import re
            new_s=re.sub(r'[^A-Za-z0-9]','',s).lower()  
    #這邊原本使用[^A-z]  會導致除了英文字母以外的字符也被加入其中,ex:_
            if new_s == new_s[-1::-1]:
                return True
            return False

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁