问题:https://leetcode.com/problems/valid-palindrome/?tab=Description
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.
**分析:**isalnum函数判断字符变量c是否为数字或者字母,若是返回非零,否则返回0。
因为按照例子的要求,pP也是回文,所以需要将字符统一一下。()toupper函数,将字符c转换为大写英文字母。
C++代码:
class Solution {
public:
bool isPalindrome(string s) {
int l=0;
int r=s.length()-1;
while(l<r){
while(!isalnum(s[l]) && l<r){
l++;
}
while(!isalnum(s[r]) && l<r){
r--;
}
if(toupper(s[l]) != toupper(s[r])) return false;
l++;
r--;
}
return true;
}
};