面试经典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;
    }
};
相关推荐
电科_银尘11 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
我不会插花弄玉12 小时前
13.多路转接epoll【由浅入深-网络】
网络·c++·epoll
郝学胜-神的一滴14 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David14 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
西西弗Sisyphus15 小时前
C++ explicit 关键字工程实践
开发语言·c++
LK_0717 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi17 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK17 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
宋艳_AI应用开发17 小时前
Agent 工程:慢的不一定是模型,答案对了也可能算失败
面试
文丑颜不良啊18 小时前
LeetCode3341~3360题目解析
java·leetcode