题目描述
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
- 示例 1:
- 输入: “A man, a plan, a canal: Panama”
- 输出: true
- 示例 2:
- 输入: “race a car”
- 输出: false
题解
1.先将字符串的大写字母全部转换为小写字母。
2.定义两个指针begin和end,遍历字符串:
(1)如果不是小写字母或数字,则后移/前移指针的位置,直至指针所指内容为字母或者数字;
(2)如果是字母或者数字,则比较begin和end所指内容是否相同:如果相同,则同时移动指针继续进行比较;如果不相同,则返回false。
class Solution {
public:
//判断是否是字母和数字字符
bool isCharorNums(char c){
if((c>= 'a' && c<='z') || (c>='0' && c<='9'))
return true;
return false;
}
bool isPalindrome(string s) {
//将大写字母转为小写字母
for(auto& ch:s){
if(ch>='A' && ch<='Z')
ch+=32;
}
int begin=0;
int end=s.size()-1;
while(begin<end){
while(begin<end && !isCharorNums(s[begin]))
++begin;
while(begin<end && !isCharorNums(s[end]))
--end;
if(s[begin]==s[end]){
++begin;
--end;
}
else
return false;
}
return true;
}
};