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.

分析

判断一个字符串是否是回文串,忽略其他字符和大小写。先将小写字母转化为大写字母,之后从首尾向中间依次判断字符和数字,不相等的话直接返回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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容