美文网首页
125. Valid Palindrome

125. Valid Palindrome

作者: RobotBerry | 来源:发表于2017-05-10 20:55 被阅读0次

问题

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

例子

"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

分析

首尾指针法

要点

判断字符是不是一个数字和字母isalnum,以及大小写转化touppertolower.

时间复杂度

O(n)

空间复杂度

O(1)

代码

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

相关文章

网友评论

      本文标题:125. Valid Palindrome

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