当前位置:网站首页>验证回文串
验证回文串
2022-06-28 14:51: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
都看到这里了,下面的内容你懂得,让我们共同进步!
边栏推荐
猜你喜欢
![[C language] how to generate normal or Gaussian random numbers](/img/31/964e0922e698a3746599b840501cdf.png)
[C language] how to generate normal or Gaussian random numbers
Technical trendsetter

vscode编写markdown文件并生成pdf

Softing epgate Pb series Gateway - integrates the Profibus bus into the ethernet/ip network

Four visualization tools are recommended to solve 99% of large screen visualization projects!

Ding! Techo day Tencent technology open day arrived as scheduled!

名创优品通过上市聆讯:寻求双重主要上市 年营收91亿

安杰思医学冲刺科创板:年营收3亿 拟募资7.7亿

币圈大地震:去年赚100万,今年亏500万

QQ被盗号后群发黄图,大批用户“社死”
随机推荐
Leetcode(406)——根据身高重建队列
Q-tester 3.2: applicable to development, production and after-sales diagnostic test software
PMP认证证书的续证费用是多少?
Performance comparison of deep learning models on cat and dog image data sets
验证回文串
[C language] how to implement plural types
@Controlleradvice + @exceptionhandler handles controller layer exceptions globally
Classmate Zhang hasn't learned to be an anchor yet
How can I get the stock account opening discount link? Is it safe to open a mobile account?
JS judge whether the string is empty or not
Is PMP really useful?
Talking from the little nematode -- tracing the evolution of nervous system and starting life simulation
安杰思医学冲刺科创板:年营收3亿 拟募资7.7亿
字节跳动埋点数据流建设与治理实践
使用LamdbaUpdateWrapper的setSql作用及风险
Leetcode (88) -- merge two ordered arrays
加油站(贪心)
324. swinging sort II: not a simple construction problem
Opening and closing principle
Ionq and Ge research confirmed that quantum computing has great potential in risk aggregation