Leetcode: Valid Palindromic

本文探讨如何通过编程方式判断一个字符串是否为回文串,即正读和反读都相同的字符串。包括两种解决方案,一种空间复杂度为O(n),另一种为O(1)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Question

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.

Hide Tags Two Pointers String


Analysis


Soluion

v1, Space Complexity O(n)

class Solution:
    # @param {string} s
    # @return {boolean}
    def isPalindrome(self, s):
        if s=='':
            return True

        s = [temp.upper() for temp in list(s)]
        s = [val for val in s if ord(val) in range(65,91) or ord(val) in range(48,58)]

        s_ori = s[:]
        s.reverse()

        return s_ori==s


v2, Space Complexity O(1)

Mistake Taken

the incorrect code is

class Solution:
    # @param {string} s
    # @return {boolean}
    def isPalindrome(self, s):
        if s=='':
            return True

        l,r = 0,len(s)-1
        while(l<=r):
            while not self.isvalid(s[l]) and l<len(s):
                l += 1

            while not self.isvalid(s[r]) and r<len(s):
                r -= 1

            if l>r or not self.issame(s[l],s[r]):
                return False


        return True

    def isvalid(self,p):
        p = p.upper()
        return True if ord(p) in range(65,91) or ord(p) in range(48,58) else False

    def issame(self,p,q):
        p,q = p.upper(), q.upper()
        return True if p==q else False

However, if the input is ″ ″, the output is False, but the expected output is True.

The solution is that in while(l<=r), moving one step(for l and r) each time. If input contains multiple ′ ′s, while(l<=r) will return nothing.


Correct code

class Solution:
    # @param {string} s
    # @return {boolean}
    def isPalindrome(self, s):
        if s=='':
            return True

        l,r = 0,len(s)-1
        while(l<=r):
            if not self.isvalid(s[l]):
                l += 1
                continue

            if not self.isvalid(s[r]):
                r -= 1
                continue

            if not self.issame(s[l],s[r]):
                return False

            l += 1
            r -= 1

        return True

    def isvalid(self,p):
        p = p.upper()
        return True if ord(p) in range(65,91) or ord(p) in range(48,58) else False

    def issame(self,p,q):
        p,q = p.upper(), q.upper()
        return True if p==q else False


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值