【Leetcode】Valid Palindrome

来源:互联网 发布:董小飒电竞淘宝店 编辑:程序博客网 时间:2024/05/16 18: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.


解题思路:设置首尾两个迭代器,从两头向中间遍历即可。只访问数字和字母(需要注意string里的字幕可能会有大小写区别,然而题目要求忽略大小写,因此比较之前需要将字母全部转换成小写或全部转换成大写)。


代码:

class Solution {public:    bool isPalindrome(string s) {        if(s.empty())return true;        string::iterator iter_front=s.begin(),iter_end=s.end()-1;        while(iter_front<iter_end){            if(!isalnum(*iter_front)){iter_front++;}            else if(!isalnum(*iter_end)){iter_end--;}            else if(tolower(*iter_front)==tolower(*iter_end)){                iter_front++;                iter_end--;            }else{                return false;            }        }        return true;    }};


0 0