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.

說明:先遍歷字符串,將所有的大寫字母轉換爲小寫字母;再將串首和串尾字符(英文字符或數字字符)依次比較,直到首尾指針指向同一地址。

代碼:

bool isPalindrome(char* s) {
    if(strlen(s) <= 1)  return true;

    char *p = s;
    while(*p != '\0')
    {
        if(isupper(*p))
            *p = tolower(*p);
        p++;
    }

    printf("%s\n", s);
    p--;

    while(s < p)
    {
        if(((*s <= 'z' && *s >= 'a') || (*s >= '0' && *s <= '9')) && ((*p <= 'z' && *p >= 'a') || (*p >= '0' && *p <= '9')))
        {
            if(*s == *p)
            {
                s++;
                p--;
            }
            else
                return false;
        }
        else if((*s <= 'z' && *s >= 'a') || (*s >= '0' && *s <= '9'))
            p--;
        else if((*p <= 'z' && *p >= 'a') || (*p >= '0' && *p <= '9'))
            s++;
        else
        {
            s++;
            p--;
        }
    }
    return true;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章