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.

 

这题直接在头尾设置两个指针,同时向中间扫面,每扫到一个数字或字母就停下来,比较是否相等,若不等就不是回文。代码如下:

 

 1 class Solution {
 2 public:
 3     bool isPalindrome(string s) {
 4         if( s.empty() ) return true;
 5         int left = 0;
 6         int right = s.length() - 1;
 7         while( left < right ) {
 8             while( left < right && !isalnum(s[left]) ) ++left;  //从左往右寻找alpha num 
 9             while( left < right && !isalnum(s[right]) ) --right;    //从右往左寻找alpha num
10             if( left < right && tolower(s[left]) != tolower(s[right]) ) return false;   //在忽略大小写的情况下,如果不等,则不是回文
11             ++left;
12             --right;
13         }
14         return true;
15     }
16 };

 

 

 

posted on 2014-08-19 23:10  bug睡的略爽  阅读(149)  评论(0编辑  收藏  举报

导航