125. 验证回文串

题目:给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。说明:本题中,我们将空字符串定义为有效的回文串。

示例 1:

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

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

1.原创

class Solution {
public:
    bool isPalindrome(string s) {
        string res1;
        for (int i=0;i<s.length();++i){
            if (isalnum(s[i]))//判断字符是否为字母
                res1+=tolower(s[i]);
        }
        if (res1.length()<2)
            return true;
        string res2 = res1;
        reverse(res1.begin(),res1.end());
        ////以上两句可以改为:string res2(res1.rbegin(), res1.rend());
        if (res1==res2)
            return true;
        else
            return false;
    }
};

2.题解

class Solution {
public:
    bool isPalindrome(string s) {
        string sgood;
        for (char ch: s) {
            if (isalnum(ch)) {
                sgood += tolower(ch);
            }
        }
        int n = sgood.size();
        int left = 0, right = n - 1;
        while (left < right) {
           if (sgood[left] != sgood[right]) {
                return false;
            }
            ++left;
            --right;
        }
        return true;
    }
};

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/valid-palindrome/solution/yan-zheng-hui-wen-chuan-by-leetcode-solution/
posted @ 2021-03-09 14:10  USTC丶ZCC  阅读(26)  评论(0编辑  收藏  举报