125. Valid Palindrome

来源:互联网 发布:mysql insert select 编辑:程序博客网 时间:2024/06/15 20:30

题目:

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.

思路:

本题思路简单,判断字符串是否为回文,属于面试经典题目,步骤如下:

1. 将字符串标点去除;

2. 将字符串中空格去除;

3. 将字符串小写字母转换为大写字母,统一表示

4. 建立两个指针指向字符串首尾,依次比较

代码:

class Solution {public:    bool isPalindrome(string s) {        if(s.size()==0)            return true;                    string::iterator itr = s.begin();        while(itr!=s.end())        {            if(ispunct(*itr))            {                s.erase(itr);                continue;            }            else if(*itr==' ')            {                s.erase(itr);                continue;            }            itr++;        }        for(int i =0;i<s.size();i++)        {            if(s[i]>='a')                s[i] -= 32;        }                    string::iterator begin = s.begin();                string::iterator end = s.end();        end--;        for(;begin<end;begin++,end--)        {            if(*begin!=*end)            return false;        }                return true;         }};