leetcode Valid Palindrome

Valid Palindrome

  Total Accepted: 19616  Total Submissions: 85566 My Submissions

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.

Have you been asked this question in an interview?  Yes

Discuss


这是一道简单题,只用考虑英文的和数字的字符,并且不区分大小写,所以直接从两头开始向中间扫描即可。

1.遇到非英文数字字符,就跳过

2.两端都是英文数字字符,就不是回文。

3.两端相遇就是回文

字符串还有几个比较方便的函数isalnum(),判断是否是数字英文字母,tolower,

tolower('a');
toupper('b');
isalpha('a');
isdigit('2');

这四个函数都是ctype.h当中的

class Solution{
public:
  bool isPalindrome(string s)
    {
        if(s.size()==0||s==""){
            return true;
        }
        int len = s.size();
        int i = 0,j = len-1;
        while(i<j)
        {
            if(!isalnum(s[i]))
            {
                i++;
                continue;
            }
            if(!isalnum(s[j]))
            {
                j--;
                continue;
            }

            char a = tolower(s[i]);
            char b = tolower(s[j]);
            if(a!=b){
                    return false;
                }
            i++;
            j--;
        }
        return true;
    }
};


你可能感兴趣的:(字符串)