forked from begeekmyfriend/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: begeekmyfriend <[email protected]>
- Loading branch information
1 parent
a576021
commit 63af633
Showing
2 changed files
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
all: | ||
gcc -O2 -o test valid_palindrome.c |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |