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.
基本思路:
題目要求,判斷一字符串,是否為符號,只考慮字母和數字,並且忽略大小寫。
用 isalnum 判斷是否為字母和數字;
用tolower將基本都作轉換小寫字母,從而在比較時忽略掉大小寫。
設置一頭一尾兩個指針,向中間移動。
此代碼在leetcode上實際執行時間為14ms。
class Solution {
public:
bool isPalindrome(string s) {
int left = 0;
int right = s.size()-1;
while (left < right) {
if (!isalnum(s[left]))
++left;
else if (!isalnum(s[right]))
--right;
else if (tolower(s[left++]) != tolower(s[right--]))
return false;
}
return true;
}
};