LeetCode 125 验证回文串

LeetCode 125 验证回文串

1. 题目地址

https://leetcode.cn/problems/valid-palindrome/?envType=study-plan-v2&envId=top-interview-150

2. 题解

    这道题比较简单,思路如下:
        1.  对源字符串进行处理,过滤掉非字母数字字符。这里需要注意:我们要将大写字母统一转换成小写。
        2.  处理过后,声明两个指针,让其相向而行。如果在移动的过程中,二者不等,那么不是回文串。如果移动过后(j < i时),二者仍然相等,那么就是回文串。其中,i代表第一个位置,j代表最后一个位置。

3. 代码

class Solution {
public:
    bool check(char str){
        if((str >= 'A' && str <= 'Z') || (str >= 'a' && str <= 'z') || (str >= '0' && str <= '9')){
            return true;
        }else{
            return false;
        }
    }
    bool isPalindrome(string s) {
        string processedStr = "";
        //去除非字符数字字符
        for(int i = 0; i < s.size(); i ++){
            if(check(s[i])){
                if(s[i] >= 'A' && s[i] <= 'Z'){
                    processedStr += s[i] + 32;
                }else{
                    processedStr += s[i];
                }
            }
        }
        //如果处理后为空字符串,则直接为回文串
        if(processedStr == ""){
            return true;
        }
        //使用双指针算法判断回文串
        for(int i = 0, j = processedStr.size() - 1; j >= i; j --,i++){
            if(processedStr[i] != processedStr[j]){
                return false;
            }
        }
        return true;
    }
};
posted @ 2023-10-09 11:47  夏目^_^  阅读(16)  评论(0)    收藏  举报