ZhongKuo0228 / study

0 stars 0 forks source link

125. Valid Palindrome #44

Open fockspaces opened 1 year ago

fockspaces commented 1 year ago

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.

fockspaces commented 1 year ago

遇到非 num, alpha 跳過,繼續比較回文

class Solution:
    def isPalindrome(self, s: str) -> bool:
        left, right = 0, len(s) - 1
        while left < right:
            while left < right and not s[left].isalnum():
                left += 1
            while left < right and not s[right].isalnum():
                right -= 1
            if s[left].lower() != s[right].lower():
                return False
            left, right = left + 1, right - 1
        return True
fockspaces commented 1 year ago

用 list comprehension 來填合法字串 接著比較反轉是否相等

class Solution:
    def isPalindrome(self, s: str) -> bool:
        filter_str = [c.lower() for c in s if c.isalnum()]
        return filter_str == filter_str[::-1]
fockspaces commented 8 months ago

use string process and reverse it to see whether reversed version is the same with itself.

class Solution:
    def isPalindrome(self, s: str) -> bool:
        process_s = "".join([c.lower() for c in s if c.isalnum()])
        return process_s == process_s[::-1]