Skip to content

Commit

Permalink
Valid palindrome
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Nov 2, 2017
1 parent a576021 commit 63af633
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 125_valid_palindrome/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test valid_palindrome.c
51 changes: 51 additions & 0 deletions 125_valid_palindrome/valid_palindrome.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

static bool valid(char c)
{
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

bool isPalindrome(char* s)
{
int len = strlen(s);
int low = 0;
int high = len - 1;

while (low < high) {
if (!valid(s[low])) {
low++;
} else if (!valid(s[high])) {
high--;
} else if (s[low] == s[high]) {
low++;
high--;
} else {
if (isalpha(s[low]) && isalpha(s[high])) {
int diff = s[low] > s[high] ? s[low] - s[high] : s[high] - s[low];
if (diff == 'a' - 'A') {
low++;
high--;
} else {
return false;
}
} else {
return false;
}
}
}

return low >= high;
}

int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "Usage: ./test string\n");
exit(-1);
}
printf("%s\n", isPalindrome(argv[1]) ? "true" : "false");
return 0;
}

0 comments on commit 63af633

Please sign in to comment.