美文网首页
Leetcode 125. Valid Palindrome

Leetcode 125. Valid Palindrome

作者: persistent100 | 来源:发表于2017-09-11 22:44 被阅读0次

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.

分析

判断一个字符串是否是回文串,忽略其他字符和大小写。先将小写字母转化为大写字母,之后从首尾向中间依次判断字符和数字,不相等的话直接返回false。

bool isalphanumeric(char s)
{
    if(s>='a'&&s<='z')return true;
    else if(s>='A'&&s<='Z')return true;
    else if(s>='0'&&s<='9')return true;
    else return false;
}
bool isPalindrome(char* s) {
    if(s[0]=='\0')return true;
    bool flag=true;
    int length=0;
    while(s[length]!='\0')
    {
        if(s[length]>='a'&&s[length]<='z')
            s[length]='A'+s[length]-'a';
        length++;
    }
    int i=0,j=length-1;
    while(i<j)
    {
        while(i<j&&isalphanumeric(s[i])==false)
            i++;
        while(i<j&&isalphanumeric(s[j])==false)
            j--;
        //printf("%c %c\n",s[i],s[j]);
        if(i==j||(i==j-1&&s[i]==s[j]))
            return true;
        else if(s[i]!=s[j])
            return false;
        else
        {
            i++;j--;
        }
    }
    return flag;
}

相关文章

网友评论

      本文标题:Leetcode 125. Valid Palindrome

      本文链接:https://www.haomeiwen.com/subject/uulqsxtx.html