leetcode125---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 low = 0;
        int high = s.size()-1;
        while(low < high)
        {
            while(low < high && !isAlphanum(s[low]))
            {//从前往后遍历,既不是字母又不数字,则略过
                low++;
            }
            while(low < high && !isAlphanum(s[high]))
            {//从后往前遍历,既不是字母又不数字,则略过
                high--;
            }//tolower()函数实现将大写转换为小写字母
            if(tolower(s[low]) != tolower(s[high]))
            {//如果对称位置的不相等
                return false;
            }
            low++;
            high--;
        }
        return true;
    }
    bool isAlphanum(char c)
    {
        return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9');
    }
};

你可能感兴趣的:(LeetCode,String)