[leetcode] 125. Valid Palindrome

Description

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上没有通过,".“和” "没有判断出来,我家了if(i>j)的操作,然后accept了,看来leetcode更难一点。

C++实现

class Solution {
public:
    bool isPalindrome(string s) {
        int i=0;
        int j=s.length()-1;
        while(i<=j){
            while(i<=j&&!isalnum(s[i])){
                i++;
            }
            while(i<=j&&!isalnum(s[j])){
                j--;
            }
            if(i>j){
                return true;
            }
            if(tolower(s[i])==tolower(s[j])){
                i++;
                j--;
            }else{
                return false;
            }
        }
        return true;
    }
};

Python实现

用python写了一个暴力解法。

class Solution:
    def isPalindrome(self, s: str) -> bool:
        i = 0
        j = len(s)-1
        while i<=j:
            if not s[i].isupper() and not s[i].islower() and not s[i].isalnum():
                i+=1
            elif not s[j].isupper() and not s[j].islower() and not s[j].isalnum():
                j-=1
            elif s[i].lower()!=s[j].lower():
                return False
            else:
                i+=1
                j-=1
        return True

下面来一个变换版本:

class Solution:
    def isPalindrome(self, s: str) -> bool:
        n = len(s)
        left = 0
        right = n-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 left<right:
                if s[left].lower()!=s[right].lower():
                    return False
                left+=1
                right-=1
        return True

上面的代码调用的API比较多,下面的简洁一点,只调用了isalnum,lower的API:

class Solution:
    def isPalindrome(self, s: str) -> bool:
        sgood = ""
        for ch in s:
            if ch.isalnum():
                sgood+=ch.lower()
        n = len(sgood)
        left = 0
        right = n-1

        while left<right:
            if sgood[left]!=sgood[right]:
                return False
            left+=1
            right-=1
        return True

参考文献

[编程题]valid-palindrome

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值