Leetcode 125. 验证回文串 双指针

地址 https://leetcode-cn.com/problems/valid-palindrome/

给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。

说明:本题中,我们将空字符串定义为有效的回文串。

示例 1:

输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:

输入: "race a car"
输出: false

解法 双指针

如果不数字和字母就移动指针 然后比较两指针指向的元素是否相同 不同则不为回文字符窜

如果全部检查完毕 则为回文字符串

代码

class Solution {
public:
    bool isPalindrome(string s) {
        transform(s.begin(), s.end(), s.begin(), ::tolower);  
        int  l =0; int r = s.size()-1;
        
        while(l < r){
            while(l <r && !isalpha(s[l]) && !isdigit(s[l])) l++;
            while(l <r && !isalpha(s[r]) && !isdigit(s[r])) r--;
            if(l<r && s[l] != s[r])  return false;
            
            l++;r--;
        }
        return true;
    }
};
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
阿里打赏 微信打赏
原文地址:https://www.cnblogs.com/itdef/p/13161299.html