Skip to content

Commit

Permalink
Wildcard matching
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Aug 29, 2017
1 parent ba41477 commit f2c3c3a
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 7 deletions.
14 changes: 7 additions & 7 deletions 010_regular_expression_matching/regular_expression.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,21 @@
#include <string.h>

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++;
Expand Down
2 changes: 2 additions & 0 deletions 044_wildcard_matching/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test wildcard_matching.c
51 changes: 51 additions & 0 deletions 044_wildcard_matching/wildcard_matching.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 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;
}

0 comments on commit f2c3c3a

Please sign in to comment.