WildCard Matching algorithm

The logic is quite simple. We do the following 3 basic checks before we do the comparison:

  1. Check for nulls and return if either of the String or Pattern is null
  2. Check if we have reached the end of string. If so, return true
  3. If either of string or pattern are left over, return false
  4. One case that we need to explicitly handle is when string is EMPTY and pattern is made solely of one or more *s.

Comparison:

  1. If it is a char or ?, skip 1 ahead in both string and pattern
  2. If it is a *, return the result of
    • string+1,pattern+1 – For handling multiple *s
    • string,pattern+1     – For handling null *
    • string+1,pattern     – For handling multi-char *

The actual code is pretty simple. The following code has a complexity of around 2^n for an sized string.

bool OnlyAskterisk(char* Pattern)
{
 if (*Pattern == '\0') return true;
 if (*Pattern != '*') return false;
 else return OnlyAskterisk(Pattern + 1);
}

bool isMatch(char *String, char *Pattern)
{
 //Base case checks
 if (*String=='\0' &&OnlyAskterisk(Pattern)) return true;
 if (!String || !Pattern) return false;
 if (*String == '\0' && *Pattern == '\0') return true;
 if (*String == '\0' || *Pattern == '\0') return false; //Tricky case which is used to eliminate stack overflows with * variable

//Actual comparisons
 if ((*String == *Pattern) || (*Pattern == '?'))
 return isMatch(String + 1, Pattern + 1);
 //Multimatch- StringMoves, No Match-PatternMoves SingleMatch- BothMove. Single match is to handle last char being *
 if (*Pattern == '*') return (isMatch(String + 1, Pattern) || isMatch(String + 1, Pattern + 1) || isMatch(String, Pattern + 1));
 return false;
}

Advertisements

3 thoughts on “WildCard Matching algorithm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s