125. Valid Palindrome(Leetcode每日一题-2020.06.19)

Problem

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.

Example1

Input: “A man, a plan, a canal: Panama”
Output: true

Example2

Input: “race a car”
Output: false

Solution

双指针

class Solution {
public:
     bool isPalindrome(string s) {
        if(s.length() <= 1)
            return true;
        
        int i = 0;
        int j = s.length() - 1;

        while(i<=j)
        {
            while(i<=j && !(isdigit(s[i]) || isalpha(s[i])))
                ++i;
            
            if(i>j)//坑爹的".,"
                return true;

            while(i<=j && !(isdigit(s[j]) || isalpha(s[j])))
                --j;
            
            if(tolower(s[i]) != tolower(s[j]))
                return false;
            
            ++i;
            --j;
            
        }

        return true;

    }
};

你可能感兴趣的:(leetcode双指针,leetcode字符串)