Leetcode刷题28-125.验证回文串(C++)

题目来源:链接: [https://leetcode-cn.com/problems/valid-palindrome/].

1.问题描述

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

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

示例1:

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

示例2:

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

2.我的解决方案

代码如下:

class Solution {
public:
    bool isPalindrome(string s) {
        int i = 0;
        int j = s.size() - 1;
        transform(s.begin(), s.end(), s.begin(), ::tolower);
        while(i<j)
        {
            if(!isalnum(s[i]))
            {
                ++i;
                continue;
            }
            if(!isalnum(s[j]))
            {
                --j;
                continue;
            }
            if(s[i++] != s[j--])
            {
                return false;
            }
        }
        return true;
    }
};
//加速专用。。。
static auto _____ = []() 
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();

3.大神们的解决方案

class Solution {
public:
    bool isPalindrome(string s) {
        string str="";
        int len=s.length();
        int lenStr=0;
        for(int i=0;i<len;i++){
            if((s[i]>='a'&&s[i]<='z')||(s[i]>='0'&&s[i]<='9')){
                str+=s[i];
                lenStr++;
            }
            else if(s[i]>='A'&&s[i]<='Z'){
                str+=(s[i]-'A'+'a');
                lenStr++;
            }
        }
        for(int i=0;i<lenStr/2;i++){
            if(str[i]!=str[lenStr-i-1]){
                return false;
            }
        }
        return true;
    }
};

4.我的收获

感觉基础不够扎实。。。

2019/3/19 胡云层 于南京 28

猜你喜欢

转载自blog.csdn.net/qq_40858438/article/details/88674628