【Leetcode】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.

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

网上找到的一个简洁版本看起来更好:

class Solution {
public:
bool isPalindrome(string s) {
	transform(s.begin(), s.end(), s.begin(), ::tolower);
	auto left = s.begin(), right = prev(s.end());
	while (left < right) {
		if (!::isalnum(*left)) ++left;
		else if (!::isalnum(*right)) --right;
		else if (*left != *right) return false;
	}
	return true;
	}
};


你可能感兴趣的:(【Leetcode】Valid Palindrome)