Runtime: 8 ms, faster than 85.46% of C++ online submissions for Valid Palindrome.
Memory Usage: 9.4 MB, less than 61.22% of C++ online submissions for Valid Palindrome.
class Solution {
public:
bool isPalindrome(string s) {
if(s.length() == 0) return true;
int i = 0;
while(i<s.length() && !isalnum(s[i])) ++i;
int j = s.length()-1;
while(j >= 0 && !isalnum(s[j])) --j;
while(i < j){
if((isalpha(s[i])&&isalpha(s[j])&&(tolower(s[i])-tolower(s[j])==0)) || (isdigit(s[i])&&isdigit(s[j])&&(s[i]==s[j]))){
i++;
while(i<s.length() &&!isalnum(s[i])) ++i;
j--;
while(j>=0&&!isalnum(s[j])) --j;
}
else
return false;
}
return true;
}
};
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
class Solution {
public:
bool isPalindrome(string s) {
if(s == "")
return true;
for(int l = 0, r = s.length()-1; l < r; l++, r--){ //多个条件
while(!isalnum(s[l]) && l < r) //isalnum函数第一次见,同时需要考虑为了躲开无效字符是否越界
l++;
while(!isalnum(s[r]) && l < r)
r--;
if(toupper(s[l]) != toupper(s[r])) return false; //toupper函数第一次见
}
return true;
}
};