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
ba41477
commit f2c3c3a
Showing
3 changed files
with
60 additions
and
7 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
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 wildcard_matching.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 isMatch(char* s, char* p) | ||
{ | ||
char *last_s = NULL; | ||
char *last_p = NULL; | ||
while(*s != '\0') { | ||
if (*p=='*'){ | ||
//skip the "*", and mark a flag | ||
p++; | ||
//edge case | ||
if (*p=='\0') return true; | ||
//use last_s and last_p to store where the "*" match starts. | ||
last_s = s; | ||
last_p = p; | ||
} else if (*p=='?' || *s == *p) { | ||
s++; | ||
p++; | ||
} else if (last_s != NULL) { | ||
// check "last_s" to know whether meet "*" before | ||
// if meet "*" previously, and the *s != *p | ||
// reset the p, using '*' to match this situation | ||
p = last_p; | ||
s = ++last_s; | ||
} else { | ||
// *p is not wildcard char, | ||
// doesn't match *s, | ||
// there are no '*' wildcard matched before | ||
return false; | ||
} | ||
} | ||
//edge case: "s" is done, but "p" still have chars. | ||
while (*p == '*') { | ||
p++; | ||
} | ||
return *p == '\0'; | ||
} | ||
|
||
int main(int argc, char **argv) | ||
{ | ||
if (argc != 3) { | ||
fprintf(stderr, "Usage: ./test string pattern\n"); | ||
exit(-1); | ||
} | ||
|
||
printf("%s\n", isMatch(argv[1], argv[2]) ? "true" : "false"); | ||
return 0; | ||
} |