LeetCode 125. 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.
*
*
************************************************************************/
c++版本 12ms,分析应该是因为重载的s[]操作耗时比c多

bool isPalindrome(string s) {
        int i = 0, j = s.size() - 1;
        while(i < j) {
            while(i < j && !isalnum(s[i])) i++;
            while(i < j && !isalnum(s[j])) j--;
            if (toupper(s[i])!=toupper(s[j]))
                return false;
            i++;j--;
        }
        return true;
    }

c版本 4ms,比c++效率高,直接使用指针的效率更高

bool isPalindrome(char* s) {
    char *p1 = s, *p2 = s + strlen(s) - 1;
    while(p1 < p2){
        if(!isalnum(*p1)){p1++;continue;}
        if(!isalnum(*p2)){p2--;continue;}
        if(tolower(*p1++) != tolower(*p2--)) return false;
    }
    return true;
}

你可能感兴趣的:(LeetCode)