125. Valid Palindrome

来源:互联网 发布:python入门要多久 编辑:程序博客网 时间:2024/06/05 09:03

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.

Solution:

class Solution {public:    bool isPalindrome(string s) {        if(s.empty()) return true;        int i = 0;        int j = s.size()-1;        while(i<j){            while(!isalnum(s[i])&&i<j) i++;            while(!isalnum(s[j])&&j>i) j--;            if(i<j&&tolower(s[i])==tolower(s[j])) {                i++;                j--;            }            else if(tolower(s[i])!=tolower(s[j])) return false;        }        return true;    }};

心得:1.大小写忽略 2 数字也要考虑(所以用isalnum()这个函数)

速度:较慢

0 0
原创粉丝点击