125. Valid Palindrome

问题

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;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容