【刷题训练】LeetCode125. 验证回文串

验证回文串

题目要求

在这里插入图片描述
示例 1:

输入: s = “A man, a plan, a canal: Panama”
输出:true
解释:“amanaplanacanalpanama” 是回文串。
示例 2:

输入:s = “race a car”
输出:false
解释:“raceacar” 不是回文串。
示例 3:

输入:s = " "
输出:true
解释:在移除非字母数字字符之后,s 是一个空字符串 “” 。
由于空字符串正着反着读都一样,所以是回文串。

提示

  • 1 <= s.length <= 2 * 105
  • s 仅由可打印的 ASCII 字符组成

解题思路

1.遍历s,将其中的大小写字符和数字保存到s1中,并且,将大写英文转换成小写。
2.使用前后指针left和right。向中间遍历,如果有不同的就返回错误。

难点:英文大小写转换方法:

  • 1.使用Ascll码。
    【小写 - 32 =大写】 ————【大写 + 32 = 小写】
  • 2.使用函数
    tolower();将大写字母转换为小写字母
    toupper();将小写字母转换为大写字母

这两个函数只会对英文字母产生作用,如果取到其他类型例如数字,会不做处理。

C++代码

class Solution {
public:
    bool isPalindrome(string s) {
        string s1;
        if(s.size()==0) return true;
        for (auto ch : s)
        {
            if ((ch >= 'a' && ch<= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9'))
            {
                if (ch >= 'A' && ch <= 'Z')
                {
                ch +=  32;
                }
            s1 += ch;
            }
        }
   
        int left =0,right = s1.size()-1;
        while(left<right)
        {
            if(s1[left]!=s1[right])
            {
                return false;
            }
            ++left;
            --right;
        }
        return true;
    }
};

使用大小写转换函数

class Solution {
public:
    bool isPalindrome(string s) {
        string s1;
        if(s.size()==0) return true;
        for (auto ch : s)
        {
            if ((ch >= 'a' && ch<= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9'))
            {
            s1 += ch;
            }
        }
        int left =0,right = s1.size()-1;
        while(left<right)
        {
            if(tolower(s1[left])!=tolower(s1[right]))
            {
                return false;
            }
            ++left;
            --right;
        }
        return true;
    }
};

相关推荐

  1. 验证算法(leetcode125)

    2024-03-15 20:52:03       39 阅读
  2. LeetCode 面试经典150 125.验证

    2024-03-15 20:52:03       12 阅读
  3. LeetCode---

    2024-03-15 20:52:03       17 阅读
  4. 125. 验证

    2024-03-15 20:52:03       12 阅读
  5. 力扣-125. 验证

    2024-03-15 20:52:03       33 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-15 20:52:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-15 20:52:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-15 20:52:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-15 20:52:03       18 阅读

热门阅读

  1. Linux磁盘管理

    2024-03-15 20:52:03       16 阅读
  2. RK3568 Ubuntu解决无法制作SD卡的问题

    2024-03-15 20:52:03       17 阅读
  3. 【vue回调函数中的 this 指向上】

    2024-03-15 20:52:03       15 阅读
  4. C++ 预编译头文件

    2024-03-15 20:52:03       21 阅读
  5. Excel百万数据如何导入导出

    2024-03-15 20:52:03       19 阅读
  6. 将PostgreSQL插件移植到openGauss指导

    2024-03-15 20:52:03       18 阅读
  7. 【TypeScript】快速掌握TypeScript的基本语法

    2024-03-15 20:52:03       19 阅读