面试经典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;
    }
};
相关推荐
孬甭_1 小时前
初识数据结构与算法
数据结构
hoiii1872 小时前
孤立森林 (Isolation Forest) 快速异常检测系统
算法
c++之路3 小时前
适配器模式(Adapter Pattern)
java·算法·适配器模式
吴声子夜歌3 小时前
Java——接口的细节
java·开发语言·算法
myheartgo-on3 小时前
Java—方 法
java·开发语言·算法·青少年编程
MonkeyKing71554 小时前
iOS 开发基础架构与运行机制(面试高频考点)
ios·面试
汉克老师4 小时前
GESP6级C++考试语法知识(四、图与树(四))
c++·贪心算法·优先队列·哈夫曼编码·哈夫曼树·gesp6级·gesp六级
宝贝儿好4 小时前
【LLM】第三章:项目实操案例:智能输入法项目
人工智能·python·深度学习·算法·机器人
子兮曰5 小时前
whisper.cpp 深度解析:从边缘设备到实时语音识别
前端·c++·后端