当前位置:网站首页>力扣每日一题-第41天-125. 验证回文串
力扣每日一题-第41天-125. 验证回文串
2022-07-22 04:32:00 【重邮研究森】
2022.7.21今天你刷题了吗?
题目:
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
分析:
给定一个包括数字,字母,其他符号的字符串,现在判断该字符串是不是回文串,也就是正序和逆序的输出一样。
思路:我们只保留字符串的数字和字母,然后把字符串逆序,判断逆序和正序是否一样即可。
解析:
1.排序
class Solution {
public:
bool isPalindrome(string s) {
string ans;
string res;
//把s的数字和字母按小写插入ans中
for (auto ch : s)
{
if (isalnum(ch))
{
ans += tolower(ch);
}
}
res = ans;
//现在判断ans是不是回文,利用逆序判断是否相等
reverse(ans.begin(),ans.end());
return res == ans;
}
};
2.双指针
通过两个指针从前后分别开始遍历,指针停止条件为left<right和当前元素为字符串和数字。当判断左右指针元素满足条件,此时判断元素内容是否一样。
class Solution {
public:
bool isPalindrome(string s) {
int left = 0;
int right = s.size() - 1;
while (left < right)
{
//一直移到字母或者数字
while (left < right && !isalnum(s[left]))
{
++left;
}
while (left < right && !isalnum(s[right]))
{
--right;
}
//当此时是数字或者字母时
if (left < right)
{
if (tolower(s[left]) != tolower(s[right]))
{
return false;
}
++left;
--right;
}
}
return true;
}
};
边栏推荐
- Fastjson code execution cve-2022-25845
- C语言程序练习——(写一个函数,它的原形是int continumax(char *outputstr,char *intputstr))
- BUUCTFReservewp(3)
- Win10 如何解决,应用商店打不开,错误代码0x80131500问题
- [ssm]ssm integration ① (integration configuration)
- Popular science | how to create a Dao?
- 用c语言编写一个函数用来删除字符串中的空格并返回空格个数
- 招股书写了“元宇宙“318次!飞天云动再战港股“元宇宙第一股“
- SFTP creation
- Methods of checking the ranking of papers and periodicals
猜你喜欢
随机推荐
MySQL查询计划key_len如何计算
梅科尔工作室——HarmonyOS应用开发培训第三次作业
Lesson 4 SSH
C#服务器NFS共享文件夹搭建与上传图片文件
[ssm]ssm integration ③ (interface test)
C # upload files to shared folders
Lecture 7 pipeline, environment variables and common commands
Typora free download compressed package (latest available)
Kalman filter program of POTU PLC signal processing series
AT4379 [AGC027E] ABBreviate
交換機與路由器技術:標准ACL、擴展ACL和命名ACL
Mysql database column splicing query writing method
【STK初探】创建一条奔月轨道
AT5662 [AGC040D] Balance Beam(二分)
像素和颜色
Screen command use
postgreSQL中update set a=(select ) 应该如何写?
[ARC116F] Deque Game
浅谈契约测试
[leetcode string -- string subscript sorting] 6121. Query the number with the smallest k after cutting the number