題目
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.
解題思路
驗證一個字符串是否是迴文字符串。首先看看wiki上對於迴文的解釋:迴文,亦稱迴環,是正讀反讀都能讀通的句子,亦有將文字排列成圓圈者,Famous examples include "Amore, Roma", "A man, a plan, a canal: Panama" and "No 'x' in 'Nixon'"。
判讀一個字符串是否是迴文,一種方法可以將字符串倒置然後和原字符串進行比較。這裏採用一種類似字符串翻轉的方法,通過從前後兩個方向來比較判斷是否是迴文。本題中的有效字符是字母和數字,並且忽略字母大小寫。
代碼如下
class Solution {
public:
bool isPalindrome(string s) {
int n = s.size();
int i=0, j=n-1;
while(i<j){
if( !isalpha(s[i]) ) {
++i;
continue;
}
if( !isalpha(s[j]) ) {
--j;
continue;
}
if(s[i] != s[j]) return false;
++i,--j;
}
return true;
}
//判斷是否是字母數字,如果是大寫字母則將其轉化爲小寫字母
bool isalpha(char &c){
if((c>='A'&&c<='Z')){
c = c-'A'+'a';
return true;
}
return (c>='a'&&c<='z') || (c>='0'&&c<='9');
}
};
另外,我開通了微信公衆號--分享技術之美,我會不定期的分享一些我學習的東西.