From f2c3c3a9c84dd6baba69da17d00f9b5697b55ef4 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 29 Aug 2017 09:46:03 +0800 Subject: [PATCH] Wildcard matching Signed-off-by: begeekmyfriend --- .../regular_expression.c | 14 ++--- 044_wildcard_matching/Makefile | 2 + 044_wildcard_matching/wildcard_matching.c | 51 +++++++++++++++++++ 3 files changed, 60 insertions(+), 7 deletions(-) create mode 100644 044_wildcard_matching/Makefile create mode 100644 044_wildcard_matching/wildcard_matching.c diff --git a/010_regular_expression_matching/regular_expression.c b/010_regular_expression_matching/regular_expression.c index 5fb6505..37c62cd 100644 --- a/010_regular_expression_matching/regular_expression.c +++ b/010_regular_expression_matching/regular_expression.c @@ -4,21 +4,21 @@ #include bool isMatch(char* s, char* p) { - if (*p=='\0') { + if (*p == '\0') { return *s == '\0'; } - //p's length 1 is special case - if (*(p+1) == '\0' || *(p+1) !='*' ) { - if (*s=='\0' || ( *p !='.' && *s != *p )) { + /* p's length 1 is special case */ + if (*(p + 1) == '\0' || *(p + 1) != '*') { + if (*s == '\0' || ( *p != '.' && *s != *p)) { return false; } else { - return isMatch(s+1, p+1); + return isMatch(s + 1, p + 1); } } int len = strlen(s); int i = -1; - while (i < len && (i <0 || *p=='.' || *p==*(s+i)) ){ - if (isMatch(s+i+1, p+2)) { + while (i < len && (i < 0 || *p == '.' || *p == *(s + i))) { + if (isMatch(s + i + 1, p + 2)) { return true; } i++; diff --git a/044_wildcard_matching/Makefile b/044_wildcard_matching/Makefile new file mode 100644 index 0000000..9543392 --- /dev/null +++ b/044_wildcard_matching/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test wildcard_matching.c diff --git a/044_wildcard_matching/wildcard_matching.c b/044_wildcard_matching/wildcard_matching.c new file mode 100644 index 0000000..c543e93 --- /dev/null +++ b/044_wildcard_matching/wildcard_matching.c @@ -0,0 +1,51 @@ +#include +#include +#include +#include + +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; +}