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

[Leetcode]-Valid Palindrome

时间:2015-07-02 22:38:27      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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、空字符也是回文
2、一定要边界判断,否则当字符串中只有特殊符号没有字母的时候就会越界,在VS2012中居然越界程序没有崩溃,LINUX中也没有。
3、不区分大小写
4、当strlen(s) < 2 一定是回文

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>

#define isstr(a)  ((a>=‘a‘&&a<=‘z‘)||(a>=‘A‘&&a<=‘Z‘)||(a>=‘0‘&&a<=‘9‘))

bool isPalindrome(char* s) {
    if(NULL == s)       return true;
    if(‘\0‘ == s)       return true;
    if(strlen(s) < 2)   return true;
    char* pa = s;
    char* pb = s;
    char* l  = s;//border of pa point
    while(*pb != ‘\0‘) pb++;
    pb--; //make pb point the last character,nor ‘\0‘!!
    char* n = pb;//border of pb point
    while(pa < pb)
    {
        while(!isstr(*pa) && pa<=n)  pa++;
        while(!isstr(*pb) && pb>=l) pb--;
        if(((*pa != *pb) && (abs(*pa-*pb) != ‘a‘-‘A‘)) && (isstr(*pa)) && (isstr(*pb)))  return false;
        else
        {
            pa++;
            pb--;
        }
    }
    return true;
}


int main()
{

    char* s = "A man, a plan, a canal: panama";
    bool r = isPalindrome(s);
    printf("s is isPalindrome? : %d \n",r);

    char *s1 = "";
    bool r1 = isPalindrome(s1);
    printf("s1 is isPalindrome? : %d \n",r1);

    char *s2 = "*.";
    bool r2 = isPalindrome(s2);
    printf("s2 is isPalindrome? : %d \n",r2);

    char *s3 = "Sore was I ere I saw Eros.";
    bool r3 = isPalindrome(s3);
    printf("s3 is isPalindrome? : %d \n",r3);

}

版权声明:本文为博主原创文章,未经博主允许不得转载。

[Leetcode]-Valid Palindrome

标签:leetcode

原文地址:http://blog.csdn.net/xiabodan/article/details/46731241

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