Valid Palindrome

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.


思路:时间是O(n),O(1)的思路是用两个指针头尾同时移动,跳过不要的字符,这里的代码为了简化代码量新建了个字符串。


class Solution {
public:
    bool isPalindrome(string s) {
        string res;
        bool flag=true;
        for(char ch:s){
            if(isalnum(ch))
                res.push_back(tolower(ch));
        }
        if(res.size()==0)
        return true;
        int i=0,k=res.size()-1;
        while (!(i == k||i==k+1)){
		    if (res[i] != res[k]){
			flag = false;
			break;
		    }
		    i++;
	    	k--;
	    }
        return flag;
    }
};


你可能感兴趣的:(算法,leetcode)