[LeetCode]Valid Palindrome

来源:互联网 发布:浩辰cad建筑软件 编辑:程序博客网 时间:2024/06/06 05:26

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.

这道题是判断一个字符串是否是回文字符串,有几个注意点:
1. 不区分大小写
2. 非数字和字母的字符忽略
3. 空字符串也认为是回文字符串

所以最一般的例子是形如,;‘’\n \t的字符串,被视为空字符串,也就是回文的。

本来准备使用额外的空间来对字符串做个预处理,后来想想,还是不必了,头尾同时遍历的时候做个判断就可以了。遇到非数字字母的字符跳过,否则判断两字符是否“相等”:互为大小写或者完全相同。我处理的方式是两者相减,判断绝对值是否是0或者32.
下面贴上代码:

class Solution {public:    bool isPalindrome(string s) {        if (s.empty())            return true;        int len = s.length();        int i = 0, j = len - 1;        while (i <= j){            while (i<len&&!isalnum(s[i]))                i++;            while (j>=0&&!isalnum(s[j]))                j--;            if (i > j)                return true;            int num = abs(s[i] - s[j]);            if (num != 0 && num != 32)                return false;            i++;            j--;        }        return true;    }};
0 0
原创粉丝点击