Valid Palindrome

题目名称
Valid Palindrome—LeetCode链接

描述
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.

分析
  一开始没看懂题目意思,然后Palindrome这种类型的题目做了好几道了,所以知道这道题也是求同构的问题,多看几遍后发现,本题的意思是给定一个字符串,只用管里面的字母和数字,看看是否同构。
  所以可以对这个字符串先进行一个处理,去掉非字母数字的字符,然后进行同构分析。我用的是一个容器vector,遍历一次给定的字符串s,把字母数字存到容器中。
  因为题目要求是忽略大小写,所以同构的时候’a’和’A’视为相同的字符,为了避免结果麻烦,在将字符存储到容器的时候将大写字母全部转换成小写字母。

C++代码

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

总结
  多看看英文题目,多理解一下不同文化之间的差异。

你可能感兴趣的:(LeetCode,String,palindrome)