LeetCode 125. Valid Palindrome 对撞指针(双索引)

来源:互联网 发布:hp5200网络打印机驱动 编辑:程序博客网 时间:2024/05/16 07:03

一、题目

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.

题意:给你一个字符串,判断当前的字符串是否为回纹串,就是首尾一一相等。

注意:题目给出只考虑数字及字母的情况,字母又分为大写和小写两种,看举例是将大小归为一起来看,这里就涉及到统一大小写的问题

          首先应该考虑当输入为空字符串的情况是否为回文,然后字符的取值范围是所有的ASCII码取值范围还是部分。

思路:和167相似,使用对撞指针也称为双索引技术。首尾两个索引,首先看这两个索引是否是字母和数字如果不是直接跳过,是数字或字母判断两者相不相等,不相等返回false,相等两个索引往里走一步,在判断是不是数字或字母。

class Solution {public:    bool isPalindrome(string s) {        transform(s.begin(), s.end(), s.begin(),::tolower);   //统一转换为小写,本应该自己写        int i=0,j=s.length()-1;        while(i<=j)        {            if((s[i]>='0'&&s[i]<='9')||(s[i]>='a'&&s[i]<='z'))     //判断是否为数字或字母            {                if((s[j]>='0'&&s[j]<='9')||(s[j]>='a'&&s[j]<='z'))                {                    if(s[i]!=s[j])           //只要其中有一对不相等,返回false                        return false;                }                else    {    j--;    continue;    }                         }            else    {    i++;    continue;    }                //继续判断下一对                i++;    j--;        }        return true;    }};

同时对比了其他写法,果然还是功力太低,冗余代码太多。尽管思路是一样的,代码简洁之道啊

 for (int i = 0, j = s.size() - 1; i < j; i++, j--) { // Move 2 pointers from each end until they collide        while (isalnum(s[i]) == false && i < j) i++; // Increment left pointer if not alphanumeric        while (isalnum(s[j]) == false && i < j) j--; // Decrement right pointer if no alphanumeric        if (toupper(s[i]) != toupper(s[j])) return false; // Exit and return error if not match    }        return true;

同时注意这几个函数的额使用

isalpha如果是字母,返回一个非零数;否则返回为0isalnum如果是字母或数字,返回一个非零数;否则返回为0isdigit如果是数字(0-9)返回一个非零数;否则返回为0

toupper单独使用是将一个字符转换为一个大写的字符

transform能将一个字符串中的大小写相互转换    template < class InputIterator, class OutputIterator, class UnaryOperator >        OutputIterator transform ( InputIterator first1, InputIterator last1,                                   OutputIterator result, UnaryOperator op );  


具体使用:http://blog.csdn.net/jerryjbiao/article/details/7523110



0 0