1.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

思路解析
仅考虑字母数字,忽略大小写,首尾相同;

  1. python示例, 两行代码。运行时间48 ms
class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        temp = [i for i in s.lower() if i in "0123456789abcdefghijklmnopqrstuvwxyz"]
        return temp == temp[::-1]

2.python示例,使用正则替换。Runtime: 24 ms, faster than 99.71% of Python online submissions for Valid Palindrome.

class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        import re
        temp = re.sub("\W+", "", s).lower()   # \W+ 用于所有与\w+不匹配的其他字符 ,详情见下方
        return temp == temp[::-1]     

附加 正则匹配点
\s:用于匹配单个空格符,包括tab键和换行符;
\S:用于匹配除单个空格符之外的所有字符;
\d:用于匹配从0到9的数字;
\w:用于匹配字母,数字或下划线字符;
\W:用于匹配所有与\w不匹配的字符;
. :用于匹配除换行符之外的所有字符。

  1. cpp示例。Runtime: 8 ms, faster than 96.25% of C++ online submissions for Valid Palindrome.
class Solution {
public:
    bool isPalindrome(string s) {
        int i = 0;
        int j = s.size() - 1;
        while(i < j){
            while(i<j && !isAlphaNumeric(s[i])) i++;
            while(j>i && !isAlphaNumeric(s[j])) j--;
            if (tolower(s[i]) != tolower(s[j]))
                return false;
            i++;
            j--;
        }
        return true;
    }
    inline bool isAlphaNumeric(char c) const{
        if (c >= 'a' && c <= 'z')
            return true;
        else if (c >= 'A' && c <= 'Z')
            return true;
        else if (c >= '0' && c <= '9')
            return true;
        else
            return false;
    }
};
  1. cpp示例,简短版本。Runtime: 12 ms, faster than 71.73% of C++ online submissions for Valid Palindrome.
class Solution {
public:
    bool isPalindrome(string s) {
        int i = 0;
        int j = s.size() - 1;
        while(i < j){
            while(i<j && !isalnum(s[i])) i++;
            while(j>i && !isalnum(s[j])) j--;
            if (tolower(s[i++]) != tolower(s[j--]))
                return false;
        }
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值