码迷,mamicode.com
首页 > 其他好文 > 详细

Valid Palindrome

时间:2014-08-19 23:57:55      阅读:475      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   strong   for   

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 };

 

 

 

Valid Palindrome,布布扣,bubuko.com

Valid Palindrome

标签:style   blog   http   color   os   io   strong   for   

原文地址:http://www.cnblogs.com/bugfly/p/3923512.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!