題目:
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Notice
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.
思路:
這題可以從左右指針來看,頭一個,尾一個,一路往中心走,走的同時要判斷是不是正確字元,可以用 isalnum 來解決,因為考慮大小寫,所以在比較的時候要使用 toupper (tolower 也行),全部統一轉換成一種大小寫來比較即可,只要一出錯就 return false.
程式:
class Solution {
public:
/**
* @param s: A string
* @return: Whether the string is a valid palindrome
*/
bool isPalindrome(string &s) {
// write your code here
if (s.empty())
return true;
int l = 0;
int r = s.size()-1;
while( l < r ) {
while(!isalnum(s[l]) && l < r)
l++;
while(!isalnum(s[r]) && l < r)
r--;
if (toupper(s[l]) != toupper(s[r]))
return false;
l++;
r--;
}
return true;
}
};