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.
在字符串前後各設一個指針,每次指向的先判別是否字母或數字,如果是小寫字母則轉爲大寫字母,再判別當前兩個指針所指向的字符是否一樣,若不一樣則不爲迴文串,跳出比較,若一樣則前後指針再查找下一組字符,終止條件爲前指針>=後指針。
class Solution {
public:
bool isPalindrome(string s) {
int len = s.length();
int i = 0, j = len - 1;
bool flag = 1;
while(i < j){
while(i < j){
if(s[i] >= 'A' && s[i] <= 'Z')break;
if(s[i] >= '0' && s[i] <= '9')break;
if(s[i] >= 'a' && s[i] <= 'z'){
s[i] -= 32;
break;
}
i++;
}
while(j > i){
if(s[j] >= 'A' && s[j] <= 'Z')break;
if(s[j] >= '0' && s[j] <= '9')break;
if(s[j] >= 'a' && s[j] <= 'z'){
s[j] -= 32;
break;
}
j--;
}
if(s[i] != s[j]){flag = 0; break;}
i++,j--;
}
return flag;
}
};