爱玩科技网
您的当前位置:首页LeetCode125:Valid Palindrome

LeetCode125:Valid Palindrome

来源:爱玩科技网

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

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

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false

LeetCode:

分两步:第一步判断字符是否是数字或者字母,第二步判断是否回文

判断字符是否是数字或者字母:如果字符在65-90(A-Z)或者97-122(a-z)或者48-57(0-9)之间,则返回true,否则false。判断是否回文:设置两个指针i=0和j=s.lenght()-1,各自从两头遍历,如果二者都是数字或字母,变小写比较大小;如果不是,就+1或-1跳过。

class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) == 0:
            return True

        def isnumalpha(c):
            if (c>='a' and c<='z') or (c>='A' and c<='Z') or (c>='0' and c<='9'):
                return True
            else:
                return False

        start = 0
        end = len(s) - 1
        while start <= end:
            if isnumalpha(s[start]) and isnumalpha(s[end]):
                if s[start].lower() != s[end].lower():
                    return False
                start += 1
                end -= 1
            elif isnumalpha(s[start]) == False:
                start += 1
            elif isnumalpha(s[end]) == False:
                end -= 1 
        return True

 

因篇幅问题不能全部显示,请点此查看更多更全内容