1委煤,輸入Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
2忧设, 空字串和單個字符返回TRUE
3崔泵, 去除空格,同時把大寫字母轉(zhuǎn)化成小寫
4险污, 二指針依次從左右夾逼比較痹愚,
bool isPalindrome(char* s) {
int len = strlen(s);
if(len == 0)
return true;
int j = 0;
//刨除掉非字母,同時把所用字符保存為小寫模式
for(int i = 0; i < len ; i++){
if(isalnum(s[i]))
s[j++] = tolower(s[i]);
}
s[j] = '\0';
if(j == 1)
return true;
int l = 0;
int r = j-1;
//l+1 很有技巧蛔糯,對于奇數(shù)拯腮,退出時候l = r, 對于偶數(shù) l + 1 = r
while(l+1<r){
if(s[l]!=s[r])
return false;
l++;
r--;
}
if(s[l]==s[r])
return true;
else
return false;
}