当前位置:网站首页>验证回文串
验证回文串
2022-06-28 14:08:00 【华为云】
title: 验证回文串
date: 2022-04-25 14:21:32
categories: LeetCode
tags: 每天进步一点点
题目
难度 简单
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: “A man, a plan, a canal: Panama”
输出: true
解释:“amanaplanacanalpanama” 是回文串示例 2:
输入: “race a car”
输出: false
解释:“raceacar” 不是回文串
提示:1 <= s.length <= 2 * 105
字符串 s 由 ASCII 字符组成
代码:
class Solution { public boolean isPalindrome(String s) { //先都转小写 s = s.toLowerCase(); StringBuilder sCopy = new StringBuilder(); for (int i = 0; i < s.length(); i++) { //自保留字母和数字 if(Character.isLetterOrDigit(s.charAt(i))) { sCopy.append(s.charAt(i)); } } //反转字符串 StringBuffer sCopy2 = new StringBuffer(sCopy).reverse(); //比较 return sCopy.toString().equals(sCopy2.toString()); }}
C++版:
#include<bits/stdc++.h>using namespace std;class Solution {public: bool isPalindrome(string s) { string str; for(char ch : s){ // 只考虑字母和数字字符 if(isalnum(ch)){ // 将字符转换为小写 str += tolower(ch); } } /** * c.rbegin() 返回一个逆序迭代器,它指向容器c的最后一个元素 * c.rend() 返回一个逆序迭代器,它指向容器c的第一个元素前面的位置 */ string str2(str.rbegin(), str.rend()); // 判断是否为回文串 return str == str2; }};int main() { Solution s; cout << (s.isPalindrome("A man, a plan, a canal: Panama") ?"true":"false")<< endl; return 0;}
以上就是验证回文串的全部内容
版权声明:
原创博主:牛哄哄的柯南
个人博客链接:https://www.keafmd.top/
看完如果对你有帮助,感谢点击下面的==一键三连==支持!
[哈哈][抱拳]
加油!
共同努力!
Keafmd
都看到这里了,下面的内容你懂得,让我们共同进步!
边栏推荐
- N皇后问题
- CVPR disputes again: IBM's Chinese draft papers were accused of copying idea, who won the second place in the competition
- 求解汉诺塔问题
- PostgreSQL超越MySQL
- Can your code talk? (upper)
- Navicat Premium 16 永久破解激活工具及安装教程(亲测可用)
- MySQL从库Error:“You cannot ‘Alter‘ a log table...“
- How to back up MySQL_ The most complete MySQL backup method in history
- PCB懂王,你是吗?我不是
- 你的代碼會說話嗎?(上)
猜你喜欢
随机推荐
PCB understand Wang, are you? I am not
Navicat Premium 16 永久破解激活工具及安装教程(亲测可用)
ThreadLocal的简单理解
Reading notes of Mr. toad going to see a psychologist
开源社邀您参加OpenInfra Days China 2022,议题征集进行中~
行动诠释价值,城联优品韩董事长出席广东英德抗洪捐赠公益活动会
线程的生命周期以及其中的方法
《蛤蟆先生去看心里医生》阅读笔记
Euler equation: a truly perfect formula in the history of mathematics!
Other domestic mobile phones failed to fill the vacancy of Huawei, and apple has no rival in the high-end mobile phone market
Latest summary! 30 provinces announce 2022 college entrance examination scores
推荐四款可视化工具,解决 99% 的可视化大屏项目!
再談exception——异常拋出時會發生什麼?
公司领导说,个人代码超10个Bug就开除,是什么体验?
Cat dog queue
Summary of 2021 computer level III database
PC博物馆-熟悉又陌生的懵懂年代
NPOI导出Excel并下载到客户端
外贸SEO 站长工具
Why will the new 5g standard bring lower TCO to the technology stack