一、题目描述
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.
题目解读:判断一个字符串是否是回文字符串,其中只有字母和数字是有效的字符,其他的字符不算。另外如果字符串为空也是一个有效的回文串应当返回true
思路:既然给的是一个string,那么很容易得到字符串的长度,那么设置两个指针,一个从前往后遍历,一个从后往前遍历。停止循环的条件是left大于等于right了。其中当碰到不是字母和数字的字符跳过即可。
c++代码(12ms,49.44%)
class Solution {
public:
bool isPalindrome(string s) {
int len = s.size(); //先获得字符串的长度
int left = 0;
int right = len-1;
while(left < right){
while(!((s[left]<='Z' && s[left] >='A') || (s[left] <= 'z' && s[left] >= 'a') || (s[left] <= '9' && s[left] >= '0')) && left<right)
left++;
while(!((s[right]<='Z' && s[right] >= 'A') || (s[right] <= 'z' && s[right] >= 'a') || (s[right] <= '9' && s[right]>= '0')) && left<right) right--;
if(left < right){
if(s[left]<='9' && s[left]>='0'){
if(s[left]!=s[right])
return false;
}else{
if((fabs(s[left]-s[right])!=0)&&(fabs(s[left]-s[right])!=32))
return false;
}//else
left++;
right--;
}//if
}//while
return true;
}
};
看了一下讨论区,思路一样,用了toupper和isalnum函数后,可以让代码更简洁,运行时间一样:
class Solution {
public:
bool isPalindrome(string s) {
for (int i = 0, j = s.size() - 1; i < j; i++, j--) { // Move 2 pointers from each end until they collide
while (isalnum(s[i]) == false && i < j) i++; // Increment left pointer if not alphanumeric
while (isalnum(s[j]) == false && i < j) j--; // Decrement right pointer if no alphanumeric
if (toupper(s[i]) != toupper(s[j])) return false; // Exit and return error if not match
}
return true;
}
};
总结:
(1)toupper函数
头文件:#include<ctype.h>
功能:将字符c转换为大写字母
原型:extern int toupper(int c)
说明:如果c为小写字母,则返回对应的大写字母;否则返回原来的值
(2)isalnum函数
头文件:#include<ctype.h>
功能:判断字符变量c是否为字母或数字
原型:extern int isalnum(int c)
说明:当c为数字0-9或字母a-z及A-Z时,返回非零值,否则返回零