125. Valid Palindrome

題目

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.

分析

題目給出一個字符串,判斷該字符串是不是回文,但是要忽略除了數(shù)字字母以外的任何字符,并且不區(qū)分大小寫,而且有空字符串的情況出現(xiàn),空字符串判定為真

解題的想法就是,先得到干凈的字符串(只有字母數(shù)字),然后首位開始依次向中間移動開始判斷

代碼

class Solution {
public:
    bool isPalindrome(string s) {
        //判斷字符串是不是為空,為空直接true 
        if(s.empty()) 
            return true;
        //去除除了字母和數(shù)字以外的所有字符 
        string str = clear(s);

        for (int i=0,j=str.length()-1;i<j;i++,j--){
            if (str[i]!=str[j]){
                return false;
            }
        }
        
        return true; 
    }
    
    //清理函數(shù),將字符串去除除了字母和數(shù)字意外的字符,并將全部字符轉(zhuǎn)為小寫 
    string clear(string s){
        string str = "";
        char c;
        for(int i=0;i<s.length();i++){
            c = s[i];
            if (c>='A'&&c<='Z' || c>='a'&&c<='z' || c>='0'&&c<='9'){
                if (c>='A'&c<='Z')
                    str+=c+32;
                else
                    str+=c;
            }
        } 
        return str;
    } 
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容