【leetcode】125 验证回文串(字符串)

题目链接:https://leetcode-cn.com/problems/valid-palindrome/

题目描述

给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。

说明:本题中,我们将空字符串定义为有效的回文串。

示例 1:

输入: "A man, a plan, a canal: Panama"
输出: true

示例 2:

输入: "race a car"
输出: false

代码

class Solution {
public:
    bool isPalindrome(string s) {
        if(s.empty() || s.size() == 1)
            return true;

        int i = 0, j = s.size()-1;
        while(i<j){
            while(i<j && !isChar(s[i])) ++i;    // 跳过非考虑字符
            while(i<j && !isChar(s[j])) --j;
            if(tolower(s[i]) == tolower(s[j])){
                ++i;
                --j;
            } else
                break;
        }
        return i>=j? true:false;
    }
    bool isChar(char ch){
        return ((ch>= 'A' && ch<='Z') ||(ch>='a' && ch<='z') || (ch>='0' && ch<='9'))?true: false;
    }
};

猜你喜欢

转载自blog.csdn.net/zjwreal/article/details/89707322