125. Valid Palindrome

Problem:

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false

思路
设置两个指针,分别从前往后和从后往前遍历,如果遇到非数字或字母字符就跳过,这里可以用isalnum()函数进行判断,非常方便,然后判断2个为数字或字母的字符是否相等。注意大小写也认为是相同的,所以可以用toupper()函数将小写都变为大写再进行比较。

Solution:

bool isPalindrome(string s) {
    for (int i = 0, j = s.size()-1; i < j; i++, j--) {
        while (!isalnum(s[i]) && i < j)    i++;
        while (!isalnum(s[j]) && i < j)    j--;
        if (toupper(s[i]) != toupper(s[j]))   return false;
    }
    return true;
}

性能
Runtime: 8 ms  Memory Usage: 9.5 MB

posted @ 2020-02-05 22:27  littledy  阅读(69)  评论(0编辑  收藏  举报