美文网首页
125. Valid Palindrome

125. Valid Palindrome

作者: 白菜炖豆腐 | 来源:发表于2016-05-24 23:28 被阅读0次

题目

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.

分析

题目给出一个字符串,判断该字符串是不是回文,但是要忽略除了数字字母以外的任何字符,并且不区分大小写,而且有空字符串的情况出现,空字符串判定为真

解题的想法就是,先得到干净的字符串(只有字母数字),然后首位开始依次向中间移动开始判断

代码

class Solution {
public:
    bool isPalindrome(string s) {
        //判断字符串是不是为空,为空直接true 
        if(s.empty()) 
            return true;
        //去除除了字母和数字以外的所有字符 
        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; 
    }
    
    //清理函数,将字符串去除除了字母和数字意外的字符,并将全部字符转为小写 
    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;
    } 
};

相关文章

网友评论

      本文标题:125. Valid Palindrome

      本文链接:https://www.haomeiwen.com/subject/dyazrttx.html