面试经典159题——Day25

文章目录

一、题目

125. Valid Palindrome

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Example 1:

Input: s = "A man, a plan, a canal: Panama"

Output: true

Explanation: "amanaplanacanalpanama" is a palindrome.

Example 2:

Input: s = "race a car"

Output: false

Explanation: "raceacar" is not a palindrome.

Example 3:

Input: s = " "

Output: true

Explanation: s is an empty string "" after removing non-alphanumeric characters.

Since an empty string reads the same forward and backward, it is a palindrome.

Constraints:

1 <= s.length <= 2 * 105

s consists only of printable ASCII characters.

题目来源: leetcode

二、题解

cpp 复制代码
class Solution {
public:
    bool isPalindrome(string s) {
        int n = s.length();
        string tmp = "";
        for(int i = 0;i < n;i++){
            if(isdigit(s[i]) || isalpha(s[i])) tmp += s[i];
        }
        int i = 0,j = tmp.length() - 1;
        while(i < j){
            if(tolower(tmp[i]) != tolower(tmp[j])) return false;
            i++;
            j--;
        }
        return true;
    }
};
相关推荐
二宝152几秒前
互联网大厂Java面试实战演练:谢飞机的三轮提问与深入解析
java·spring boot·redis·微服务·面试·kafka·oauth2
ytttr8734 分钟前
MATLAB ViBe算法视频前景提取完整实现
算法·matlab·音视频
见叶之秋4 分钟前
【数据结构】详解栈和队列
数据结构
你撅嘴真丑5 分钟前
和为给定数 与 最匹配的矩阵
c++·算法·矩阵
MimCyan7 分钟前
LeetCode hot 100 (8-11,自用2026.04.03)
leetcode
南境十里·墨染春水7 分钟前
C++ 笔记:std::bind 函数模板详解
前端·c++·笔记
Book思议-8 分钟前
【数据结构】二叉树小题
数据结构·算法
CoderCodingNo11 分钟前
【GESP】C++五级练习题 luogu-P1303 A*B Problem | 高精度计算
数据结构·c++·算法
故事和你9111 分钟前
洛谷-算法1-1-模拟与高精度2
开发语言·数据结构·c++·算法·动态规划
B1acktion11 分钟前
2.6.堆排序——从堆结构到 Top-K,一套思路贯穿排序与选择
数据结构·c++·算法·排序算法