125. Valid Palindrome

经典中的经典题。奇怪的是like的人不多。
先是老老实实的写了个list,把奇奇怪怪的字符给去掉了。
果然很慢。但是程序可读性杠杆的。

class Solution:
    def isPalindrome(self, s: str) -> bool:
        def isLower(c):
            if ord(c) >= ord('a') and ord(c) <= ord('z'):
                return True
            return False
        
        def isCapital(c):
            if ord(c) >= ord('A') and ord(c) <= ord('Z'):
                return True
            return False
        
        def isNumeric(c):
            if ord(c) >= ord('0') and ord(c) <= ord('9'):
                return True
            return False
        
        # first only save the 'good' lowercase chars -- alphanumeric
        clean_list = []
        for i in range(len(s)):
            if isNumeric(s[i]):
                clean_list.append(s[i])
            elif isCapital(s[i]):
                clean_list.append(s[i].lower())
            elif isLower(s[i]):
                clean_list.append(s[i])
                
        # then from the middle, check wheher they are symmetric
        if len(clean_list) == 0:
            return True
        
        i=0
        j=len(clean_list)-1
        while i<j:
            if clean_list[i] != clean_list[j]:
                return False
            i += 1
            j -= 1
        return True

改进下,去掉clean_list,直接左右比较,还是太慢。咋回事?
估计是Python3行数太多的缘故。

class Solution:
    def isPalindrome(self, s: str) -> bool:
        def isLower(c):
            if ord(c) >= ord('a') and ord(c) <= ord('z'):
                return True
            return False
        
        def isCapital(c):
            if ord(c) >= ord('A') and ord(c) <= ord('Z'):
                return True
            return False
        
        def isNumeric(c):
            if ord(c) >= ord('0') and ord(c) <= ord('9'):
                return True
            return False
        
        def getNextLeft(s, i):
            while i<len(s): 
                if isLower(s[i]) or isNumeric(s[i]):
                    return (s[i],i+1)
                elif isCapital(s[i]):
                    return (s[i].lower(), i+1)
                i+=1
            return(None, i)
        
        def getNextRight(s, j):
            while j>=0: 
                if isLower(s[j]) or isNumeric(s[j]):
                    return (s[j],j-1)
                elif isCapital(s[j]):
                    return (s[j].lower(), j-1)
                j-=1
            return(None, j)
        
                
        # then from the middle, check wheher they are symmetric
        if len(s) == 0:
            return True
        
        i=0
        j=len(s)-1
        while i<j:
            a,i = getNextLeft(s, i)
            b,j = getNextRight(s, j)
            if a != b:
                return False

        return True

搞了半天,Python3有个叫isalnum()的函数,一下就把一大堆自定义函数删了。

class Solution:
    def isPalindrome(self, s: str) -> bool:       
        # then from the middle, check wheher they are symmetric
        if len(s) == 0:
            return True
        
        i=0
        j=len(s)-1
        while i<j:
            if s[i].isalnum() and s[j].isalnum():
                if s[i].lower() != s[j].lower():
                    return False
                i+=1
                j-=1
            elif not s[i].isalnum():
                i+=1
            elif not s[j].isalnum():
                j-=1

        return True

Python版的充分利用了Python3的函数,比如构造string,string reverse等。

class Solution:
    def isPalindrome(self, s: str) -> bool:       
        # then from the middle, check wheher they are symmetric
        if len(s) == 0:
            return True
        
        clean = ''.join(char.lower() for char in s if char.isalnum())
        #clean = clean.lower()

        if clean[::-1] != clean:
            return False

        return True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值