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"]
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;
}

[/code]

3 comments:

  1. What would happen if the input is an empty string and the pattern is a*

    ReplyDelete
  2. Thanks for pointing the mistake out. I've updated the code to handle the edge. Do let me know in case you find any more issues.

    ReplyDelete
  3. What would happen if the input is string = "*AB" and pattern = "*?"

    ReplyDelete

GraphQL

GraphQL What is GraphQL It is a specification laid out by Facebook which proposed an alternative way to query and modify data. Think o...