Leetcode 验证回文字符串

本文最后更新于:2022年3月23日 晚上

地址:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/5/strings/36/

题目

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

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

示例 1:

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

示例 2:

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

我的解决方案

class Solution {
public:
    bool isPalindrome(string s) {
        bool bl = true;    //作为返回值
        string sta;   //定义一个字符串sta将原字符串s标准化
        for (int i = 0; i < s.size(); i++) {   //将原字符串s除字母和数字外的字符去除并将大写字母全部转换为小写字母
            if ((s[i] >= 48 && s[i] <= 57) || (s[i] >= 97 && s[i] <= 122)) {
                sta += s[i];
            }
            if (s[i] >= 65 && s[i] <= 90) {
                sta += char(s[i] + 32);
            }
        }
        int n = sta.size();   //字符串sta的字符个数
        for (int j = 0; j < sta.size() / 2; j++) {   //判断是否回文串
            if (sta[j] != sta[n - 1 - j]) {   //说明不是回文串,将bl置为false并跳出循环,后续不必再判断
                bl = false;
                break;
            }
        }
        return bl;
    }
};

Leetcode 验证回文字符串
https://mxy493.xyz/2019020249412/
作者
mxy
发布于
2019年2月2日
许可协议