- Check for nulls and return if either of the String or Pattern is null
- Check if we have reached the end of string. If so, return true
- If either of string or pattern are left over, return false
- One case that we need to explicitly handle is when string is EMPTY and pattern is made solely of one or more *s.
Comparison:
- If it is a char or ?, skip 1 ahead in both string and pattern
- 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]