125. Valid Palindrome

来源:互联网 发布:淘宝智能版首页全屏 编辑:程序博客网 时间:2024/05/21 17:50

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.


判断字符串是否是回文的,注意只考虑字母和数字,且忽略大小写。通过两头向中间移动的方法逐个比较,如果有不一样的一对字符就返回false。最后如果有l>=r的话说明检测完毕,返回true。


代码:

class Solution{public:bool isPalindrome(string s){int l = 0, r = s.size() - 1;while(l < r){while(!isalnum(s[l])) ++l;while(!isalnum(s[r])) --r;if(l >= r) break;if(toupper(s[l]) != toupper(s[r])){return false;}++l; --r;}return true;}};