1. 程式人生 > >LeetCode Valid Palindrome

LeetCode Valid Palindrome

Problem

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example, “A man, a plan, a canal: Panama” is a palindrome. “race a car” is not a palindrome.

Note: Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

即判斷一個字串的字元部分是不是迴環字串。即出去非字母,數字以外的字元,剩下的部分滿足正反相同。

Python實現


'''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.
'''
# author li.hzh class Solution: def isPalindrome(self, s): """ :type s: str :rtype: bool """ if len(s) == 0: return True front_index, end_index = 0, len(s) - 1 while front_index < end_index: if not s[front_index]
.isalnum(): front_index += 1 continue if not s[end_index].isalnum(): end_index -= 1 continue if s[front_index].lower() != s[end_index].lower(): return False else: front_index += 1 end_index -= 1 return True print(Solution().isPalindrome("A man, a plan, a canal: Panama")) print(Solution().isPalindrome("race a car"))

分析

很直接的思路,首尾兩個指標,依次過濾字元進行判斷。有不相等即返回False。

還有一個思路,程式碼很簡單。先用正則去掉所有的非字母數字的字元,然後判斷原字串與逆序的字串相等即可。該思路用python的re包實現非常簡單。

class Solution:
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        import re
        s = re.sub(r'[^A-Za-z0-9]', '', s).lower()
        return s == s[::-1]