[leetcode]125. 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

分析:

验证是否为回文字符串,只考虑字母和数字,忽略大小写。可以用双指针分别从头和尾依次遍历,遇到非字母数字字符则跳过,否则比较是否相等,出现不一样的就返回false,若两指针相遇仍相等则为true。其中需要注意的是不区分字母的大小写,由于小写字母的ACSCII码值比大写字母大32,所以%32求余数,余数相等则认为是相同字符。

class Solution {
public:
    bool isPalindrome(string s) {
        int left = 0;
        int right = s.size()-1;
        while(left < right)
        {
            if(!isalphanum(s[left]))
                left++;
            else if(!isalphanum(s[right]))
                right--;
            else if((s[left]+32-'a')%32 != (s[right]+32-'a')%32)
            {
                return false;
                         
            }   
            else
            {
                left++;
                right--;
                    
            }
        }
        return true;
                        
    }
       bool isalphanum(char &c)
        {
            if(c>='a' && c<='z')
                return true;
            if(c>='A' && c<='Z')
                return true;
            if(c>='0' && c<='9')
                return true;
            else
                return false;                                           
        }
        
};

猜你喜欢

转载自blog.csdn.net/weixin_41814716/article/details/84169585
今日推荐