2018LeeCode算法题解一之Valid Palindrome

看到此文,是否觉得体内洪荒之力爆发,饥渴难耐想吐槽、情不自禁想捐赠
本文为原创文章,尊重辛勤劳动,可以免费摘要、推荐或聚合,亦可完整转载,但完整转载需要标明原出处,违者必究。

支付宝微  信

原题

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.

原题链接:https://leetcode.com/problems/valid-palindrome/description/

代码

C++

class Solution {
public:
    bool isPalindrome(string s) {
        if (s.length() == 0) return true;
        // filter
        string fs;
        for (int i = 0; i < s.length(); ++i) {
            if ((48 <= s[i] && s[i] <= 57) || (65 <= s[i] && s[i] <= 90) || (97 <= s[i] && s[i] <= 122)) {
                if (65 <= s[i] && s[i] <= 90) s[i] = tolower(s[i]);
                fs.append(s, i, 1);
            }
        }
        
        int fsl = fs.length();
        for (int i = 0; i < fsl / 2; ++i) 
           if (fs[i] - fs[fsl - i - 1] != 0) return false;
        
        return true;
    }
};

Python

import re
class Solution:
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        s = re.sub('[^A-Za-z0-9]', '', s).lower()       
        return s == s[::-1]

原文链接:胡小旭 => 2018LeeCode算法题解一之Valid Palindrome


分类: C/C++, Python, 技术, 算法, 编程 | 标签: , , , , , , | 评论 | Permalink

发表评论

电子邮件地址不会被公开。 必填项已用*标注