leetcode[125] Valid Palindrome

判断一个字符串是不是回文,忽略其中的非数字和非字母,例如符号和空格不考虑。

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.

想到用reverse函数:

class Solution {

public:

bool isPalindrome(string s)

{

    int len = s.size(), i = 0, j = 0;

    if (len < 2) return true;

    string revs = s;

    reverse(revs.begin(), revs.end());

    while(i < len && j < len)

    {

        while(i < len && !isdigit(s[i]) && !isalpha(s[i])) i++; // isalnum();

        while(j < len && !isalnum(revs[j])) j++;

        if (toupper(s[i++]) != toupper(revs[j++]))

            return false;

    }

    return true;

}

};

不用的话就:

class Solution {

public:

bool isPalindrome(string s)

{

    int len = s.size(), i = 0, j = len - 1;

    if (len < 2) return true;

    while(i < len && j >= 0)

    {

        while(i < len && !isalnum(s[i])) i++;

        while(j >= 0 && !isalnum(s[j])) j--;

        if( i < len && j >= 0 && toupper(s[i++]) != toupper(s[j--])) //注意要先判断ij是否合法

            return false;

    }

    return true;

}

};

提交第一个时,出现了:

Congratulations, you've just unlocked a solution! 

leetcode[125] Valid Palindrome

之前没碰见过,不知道是不是新的功能。然后点进去是评价的界面。给评了个5分。

界面说:The idea is simple, have two pointers – one at the head while the other one at the tail. Move them towards each other until they meet while skipping non-alphanumeric> characters.

你可能感兴趣的:(LeetCode)