LeetCode 125

問題描述:

給定一個字符串,驗證它是否是迴文串,只考慮字母和數字字符,可以忽略字母的大小寫。

說明:本題中,我們將空字符串定義爲有效的迴文串。

示例 1:

輸入: "A man, a plan, a canal: Panama"
輸出: true
示例 2:

輸入: "race a car"
輸出: false

class Solution {
public:
    bool isPalindrome(string s) {
        vector<char> vec;
        for(int i=0;i<s.length();i++){
            if((s[i]>='a'&& s[i]<='z')||(s[i]>='A'&& s[i]<='Z')||(s[i]>='0'&& s[i]<='9')){
                if(s[i]>='A'&& s[i]<='Z'){
                    s[i] = s[i]+32;
                }
                vec.push_back(s[i]);
            }
        }
        for(int i=0;i<vec.size()/2;i++){
            if(vec[i]!=vec[vec.size()-1-i]) return false;
        }
        return true;
    }
};

還有一種雙指針解法,可以看看

class Solution {
public:
    bool isPalindrome(string s) {
        if(s.length()<=1)    return true;
        int i=0,j = s.size()-1;
        while(i<j){
            while(i<j && !isalnum(s[i])) i++;
            while(i<j && !isalnum(s[j])) j--;
            if(tolower(s[i++])!=tolower(s[j--])) return false;
            
        }
        return true;
    }
        //isalnum(char c):判斷字符變量c是否爲字母或數字,若是則返回非零,否則返回零。 tolower(char c):把字母字符          
//轉換成小寫,非字母字符不做出處理。
};
          

 

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