程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> [Leetcode]-Valid Palindrome

[Leetcode]-Valid Palindrome

編輯:C++入門知識

[Leetcode]-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、空字符也是回文
2、一定要邊界判斷,否則當字符串中只有特殊符號沒有字母的時候就會越界,在VS2012中居然越界程序沒有崩潰,LINUX中也沒有。
3、不區分大小寫
4、當strlen(s) < 2 一定是回文

#include 
#include 
#include 
#include 
#include 

#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('' == s)       return true;
    if(strlen(s) < 2)   return true;
    char* pa = s;
    char* pb = s;
    char* l  = s;//border of pa point
    while(*pb != '') pb++;
    pb--; //make pb point the last character,nor ''!!
    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 
,r);

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

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

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

}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved