[每日一题]18:验证回文串

题目描述

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

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

示例 1:

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

示例 2:

输入: “race a car”
输出: false

思路:

  1. 从字符串开头与末端同时遍历字符串

  2. 先判断字符串这个位置的字符是不是字母和数字字符(写一个函数)

  3. 如果是,则保存下标,跳出循环(在此过程将大小写字母,规整划一);不是的话,则跳过本字符,检测下个字符

  4. 通过对比前后下标对应的字符,判断字符串是否为回文串

代码如下:

bool IsNumber(char c){
    return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

class Solution {
public:
    bool isPalindrome(string s) {
        if(s.empty())
            return true;

        int start = 0;
        int end = s.size() - 1;

        while(start < end){
            while(start != end){
                if(IsNumber(s[start])){
                    if((s[start] >= 'A' && s[start] <= 'Z')){
                        s[start] += 32;
                    }
                    break;
                }
                    
                ++start;
            }

            while(start != end){
                if(IsNumber(s[end])){
                    if((s[end] >= 'A' && s[end] <= 'Z')){
                        s[end] += 32;
                    }
                    break;
                }
                
                --end;
            }

            if(s[start] == s[end]){
                ++start;
                --end;
            }
            else{
                return false;
            }
        }
        return true;
    }
};

//验证代码
int main() {
    Solution S;
    string str;
    getline(cin, str);
    if(S.isPalindrome(str))
        cout << "true" << endl;
    else
        cout << "false" << endl;

    return 0;
}

代码生成图
在这里插入图片描述


如有不同意见,欢迎留言讨论~

发布了152 篇原创文章 · 获赞 45 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/AngelDg/article/details/105047183