LeetCode125—Valid Palindrome

LeetCode125—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.

Subscribe to see which companies asked this question

分析

回文串问题,由于题目说了,只考虑数字和字母(字母不区分大小写),不知道有没有更高端的算法,但是至少做下面几步是可行的:

  1. 去其他符号只保留字母数字。
  2. 把余下的字符串分为两半。
  3. 一半从前往后一半从后往前,逐个字符比较。

代码

class Solution {
private:
    bool compareIgnoreCase(string const& s1, string const&s2)
    {
        return equal(s1.begin(), s1.end(), s2.begin(), 
        [](char a, char b){return tolower(a) == tolower(b); });//Lambda
    }
    void removeSyntex(string &s)//删去非法字符
    {
        string tmp;
        for (int i = 0; i < s.size(); i++)
        {
            if (isalnum(s[i]))
            {
                tmp += s[i];
            }
        }
        s = tmp;
    }
public:
    bool isPalindrome(string s) {
        removeSyntex(s);
        if (s.size() == 0)
            return true;
        int mid;
        mid = s.size() / 2;
        string leftSubString(s.begin(), s.begin() + mid);//前半
        string rightSubString(s.rbegin(), s.rbegin() + mid);//后半
        return compareIgnoreCase(leftSubString, rightSubString);
    }
};

补充:
在C++使用静态成员函数说到:
这里在比较函数使用了Lambda表示,事实上,完全可以写一个比较函数:

bool cmp(char a,char b)
{
    return tolower(a) == tolower(b);
}

如果这样的话,必须是:

  1. 要不然在类外部声明定义
  2. 要不然在类中声明成static成员函数
  3. 要不然就是用boost库( boost::bind)

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