题目如下:
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.
分析如下:/
一开始,为了防止超时,就打算直接一边用一头一尾两个指针扫描字符串,一边做判断,扫描一次完成所有的任务。后来从网上的答案来看,其实也可以先做大小写转换再判断的。算是被之前总是超时的经历给矫枉过正了。。。是一道简单但是需要不容易一次提交通过的题目,需要非常仔细需要把所有的case考虑到。
我的代码:
// 100ms过大集合
//ascii码中的数字(0~9) 48 57
//ascii码中的字符(A~Z) 65 90
//ascii码中的字符(a~z) 97 122
class Solution {
public:
bool isPalindrome(string s) {
int i=0;
int j=(int)s.length()-1;
if(j==-1)
return true;
while(i<j){
if((s[i]>=48)&&(s[i]<=57)&&(s[j]>=48)&&(s[j]<=57)&&(s[i]!=s[j])){
return false;
}else if((s[i]>=65)&&(s[i]<=90)&&(s[j]>=65)&&(s[j]<=90)&&(s[i]!=s[j])){
return false;
}else if((s[i]>=97)&&(s[i]<=122)&&(s[j]>=97)&&(s[j]<=122)&&(s[i]!=s[j])){
return false;
}else if((s[i]>=65)&&(s[i]<=90)&&(s[j]>=97)&&(s[j]<=122)&&(s[i]+32!=s[j])){
return false;
}else if((s[j]>=65)&&(s[j]<=90)&&(s[i]>=97)&&(s[i]<=122)&&(s[j]+32!=s[i])){
return false;
}else if((s[i]<48)||((s[i]>57)&&(s[i]<65))||((s[i]>90)&&(s[i]<97))||(s[i]>122)){
i++;
}else if( (s[i]>=48)&&(s[i]<=57)&&(((s[j]>=65)&&(s[j]<=90))||((s[j]>=97)&&(s[j]<=122))) ){
return false;
}else if((s[j]>=48)&&(s[j]<=57)&&(((s[i]>=65)&&(s[i]<=90))||((s[i]>=97)&&(s[i]<=122)))){
return false;
}else if((s[j]<48)||((s[j]>57)&&(s[j]<65))||((s[j]>90)&&(s[j]<97))||(s[j]>122)){
j--;
}else{
i++;
j--;
}
}
return true;
}
};
update: 2014-12-04
两个指针,分别指向一头一尾,如果其中任何一个不是alfanumeric就跳过,否则就进行比较。如果比较结果不符合要求,就返回false,否则就一直比较直到两个指针相遇为止,此时结果返回true.
class Solution {
public:
bool isAlphanumeric(char c) {
return ((c -'0'>=0)&&(c - '0' <=9)) ||
( (c - 'a'>=0)&&(c - 'a'<=25)) ||
( (c - 'A'>=0)&&(c - 'A'<=25)) ;
}
bool isEqualIgoreCase(char c1, char c2) {
return (c1 - 'A' == c2 - 'A') ||
(c1 - 'a' == c2 - 'a') ||
(c1 - 'A' == c2 - 'a') ||
(c1 - 'a' == c2 - 'A') ;
}
bool isPalindrome(string s) {
if (s.length()==0) return true; //写为 if (s.length()==1) return true 也OK.
int i = 0, j = s.length() -1;
while (i <= j) {
if (isAlphanumeric(s[i]) && isAlphanumeric(s[j])) {
if (isEqualIgoreCase(s[i], s[j])) {
i++;
j--;
} else {
return false;
}
}else{
if (!isAlphanumeric(s[i]))
i++;
if (!isAlphanumeric(s[j]))
j--;
}
}
return true;
}
};