【一天一道LeetCode】#125. Valid Palindrome

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处

(一)题目

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.

(二)解题

题目大意:判断一个字符串是不是有效的回文字符串。忽略里面除了数字和字母的其他字符。
解题思路:两个指针i和j,i从前往后,j从后往前,碰到p[i]和p[j]都是字母或者数字就比较大小,如果相等就i++,j–反之则返回false

直到i>=j时,说明是有效回文,返回true。

//isalnum()是判断该字符是不是字母或数字
class Solution {
public:
    bool isPalindrome(string s) {
        int len = s.length();
        int i = 0;
        int j = len-1;
        while(i<=j)
        {
            while(!isalnum(s[i])&&i<=j) i++;//直到s[i]为字母或数字为止
            while(!isalnum(s[j])&&i<=j) j--;//直到s[j]为字母或数字为止
            if(i<=j&&tolower(s[i])!=tolower(s[j])) return false;//如果不等就返回false
            i++;j--;//反之就继续比较
        }
        return true;
    }
};

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