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;
    }
};

猜你喜欢

转载自www.cnblogs.com/itdef/p/13161299.html