Effective way of checking if a given string is palindrome in C -
i preparing interview , started working simple c programming questions. 1 question came across check if given string palindrome. wrote a code find if user given string palindrome using pointers. i'd know if effective way in terms of runtime or there enhancement it. nice if suggests how remove other characters other letters (like apostrophe comas) when using pointer.i've added function below. accepts pointer string parameter , returns integer.
int palindrome(char* string) { char *ptr1=string; char *ptr2=string+strlen(string)-1; while(ptr2>ptr1){ if(tolower(*ptr1)!=tolower(*ptr2)){ return(0); } ptr1++;ptr2--; } return(1); }
"how remove other characters other letters?"
i think don't want remove it, skip , use isalpha so. note condition ptr2 > ptr1 work strings amount of characters such abba, strings such abcba, condition should ptr2 >= ptr1:
int palindrome(char* string) { size_t len = strlen(string); // handle empty string , string of length 1: if (len == 0) return 0; if (len == 1) return 1; char *ptr1 = string; char *ptr2 = string + len - 1; while(ptr2 >= ptr1) { if (!isalpha(*ptr2)) { ptr2--; continue; } if (!isalpha(*ptr1)) { ptr1++; continue; } if( tolower(*ptr1) != tolower(*ptr2)) { return 0; } ptr1++; ptr2--; } return 1; } you might need #include <ctype.h>
Comments
Post a Comment