Leetcode 125. Valid Palindrome

本文介绍了一种使用双指针方法判断字符串是否为回文的有效算法,该算法仅考虑字母数字字符并忽略大小写差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

题目大意:给一个字符串,判断它是否是回文,只考虑字母数字字符,并且忽略大小写。

分析:可用双指针解决,i指向头,j指向尾,先用tolower()函数(如果是大写字母才将其转换为小写字母,否则不变),将大写字母转换为小写字母,如果s[i]和是s[j]都是字母,判断是否相等,如果不相等,直接返回false,否则i++,j--;如果有一个不是字母,那么对应移动指针。循环条件i <= j;循环结束后还没有返回,则说明是回文,返回true;

 1 class Solution {
 2 public:
 3     bool isAlphanumericCharacters(char s){
 4         return (s >= 'a' && s <= 'z') || (s >= '0' && s <= '9');
 5     }
 6     bool isPalindrome(string s) {
 7         int len = s.length();
 8         if(len == 0)
 9             return true;
10         for(int i = 0, j = len - 1; i <= j; ){
11             char c1 = tolower(s[i]), c2 = tolower(s[j]);
12             //如果c1和c2都是字母;
13             if(isAlphanumericCharacters(c1) && isAlphanumericCharacters(c2)) {
14                 //判断是否相等
15                 if(c1 == c2){
16                     i++;
17                     j--;
18                 //不相等直接返回false;
19                 } else {
20                     return false;
21                 }
22             //如果c1是字母,c2不是字母
23             } else if (isAlphanumericCharacters(c1) && !isAlphanumericCharacters(c2)){
24                 j--;
25             //如果c1不是字母,c2是字母;
26             } else if (!isAlphanumericCharacters(c1) && isAlphanumericCharacters(c2)){
27                 i++;
28             //都不是字母
29             } else {
30                 i++;
31                 j--;
32             }
33         }
34         return true;
35     }
36 };

 

转载于:https://www.cnblogs.com/qinduanyinghua/p/5843717.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值