Valid Palindrome

来源:互联网 发布:网络信息安全检查表 编辑:程序博客网 时间:2024/05/29 16:10

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.length() == 0 || s.length() == 1) {            return true;        }                int low = 0;        int high = s.length()-1;            while(low < high) {            if(!isValidChar(s[low])){                low++;                continue;              }                        if(!isValidChar(s[high])) {                high--;                continue;            }                        if(tolower(s[low]) != tolower(s[high])) {                return false;            }            else {                low++;                high--;            }                }                return true;    }        bool isValidChar(char ch) {        return (ch >= 'a' && ch <= 'z' ||                ch >= 'A' && ch <= 'Z' ||                ch >= '0' && ch <= '9');    }};


0 0