## Thursday, March 13, 2014

### 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.

[code language="cpp"]
{
if (*Pattern == '\0') return true;
if (*Pattern != '*') return false;
}

bool isMatch(char *String, char *Pattern)
{
//Base case checks
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;
}

[/code]