[LeetCode] Valid Palindrome [10]

題目

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');
    }
};

如果你覺得本篇對你有收穫,請幫頂。
另外,我開通了微信公衆號--分享技術之美,我會不定期的分享一些我學習的東西.
你可以搜索公衆號:swalge 或者掃描下方二維碼關注我

(轉載文章請註明出處: http://blog.csdn.net/swagle/article/details/28883129 )

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章