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.
回文字符串判斷,但只判斷字母和數字是不是構成回文字符串,標點符號被略過。
保存左右兩個指針,每輪先移動左指針獲得1個字母或數字,其它字符都跳過;然后移動右指針,找到1個字母或數字,其它字符都跳過;如果此時左右兩個字符都為字母或數字并但是兩個不相等,則返回false
;進行下輪指針移動直到兩個指針相等。
class Solution {
public:
bool isPalindrome(string s) {
if(s.length()==0||s.length()==1) return true;
int left=0, right=s.length()-1;
// 大寫轉小寫
for(int i=0;i<s.length();i++) {
char ch = s[i];
if(ch>='A'&&ch<='Z') ch = 'a' + ch - 'A';
s[i] = ch;
}
while(left<right) {
char l = s[left++];
char r = s[right--];
while(!((l>='a'&&l<='z')||(l>='0'&&l<='9'))&&left<s.length()) {
l = s[left++];
}
while(!((r>='a'&&r<='z')||(r>='0'&&r<='9'))&&right>0) {
r = s[right--];
}
if(((l>='a'&&l<='z')||(l>='0'&&l<='9'))&&((r>='a'&&r<='z')||(r>='0'&&r<='9'))&&r!=l) {
return false;
}
}
return true;
}
};
下一篇 LTE 網絡UE端測量