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.
-----------------------------
要注意 因為我在 27跟28 還有30
是直接傳s[head]進去函數 所以她是傳一個char進去
如果想要bool isalqh(char *s) 用指標去接
那在外面必須要把記憶體位置傳進去 &s[head]
還有數字也算字母
別忘了要轉乘一樣的字母大小
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | bool isalqh(char s){//we only get a char inside , not char *s int alqh=(int)s; //not *s //printf("%d ",alqh); if( alqh >= 'A' && alqh <='Z' )return true; else if( alqh >='a' && alqh<='z' )return true; else if ( alqh >='0' && alqh<='9' )return true; else return false; } bool isans(char s1,char s2){//not *s1 int s1lower=(int)s1; int s2lower=(int)s2; if( s1lower >= 'A' && s1lower <='Z' )s1lower+=('a'-'A');//change to lowwer cast if( s2lower >= 'A' && s2lower <='Z' )s2lower+=('a'-'A');//change to lowwer cast //printf("%c %c\n",s[head],s[end]); if(s1lower==s2lower)return true; else return false; } bool isPalindrome(char* s) { int size=strlen(s); if(!*s)return true; //empyt is true int head=0,end=size-1; while(head<end){ while(head<size && !isalqh(s[head]))head++; while(end>=0 && !isalqh(s[end]))end--; //printf("%c %c\n",s[head],s[end]); if(!isans(s[head],s[end]))return false; head++; end--; } return true; } |
------------------
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class Solution { public: bool isPalindrome(string s) { int size=s.length(); int left=0,right=size-1; if(size==0)return true; while(left<right){ while(left<size && !Isalph(s[left]))left++; while(right>0 && !Isalph(s[right]))right--; if(left<right && s[left]!=s[right])return false; left++; right--; } return true; } private: bool Isalph(char &s){ if( (s>='a' && s<='z') || ( s>='0' && s<='9' ) )return true; else if( s>='A' && s<='Z' ){ s= s+'a'-'A'; return true; }else return false; } }; |
沒有留言:
張貼留言