Online Judge Solutions

Thursday, November 20, 2014

Wildcard Matching

Wildcard Matching
Implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false

 
// Solution 1
class Solution {
public:
    bool isMatch( const char *s, const char *p) {
       while(*s && *p != '*') {
           if (*s != *p && *p != '?') return false;
           s++;
           p++;
       }
      
       const char *ps = NULL;
       const char *pp = NULL;
       while(*s) {
           if (*p == '*') {
               if (!*++p) return true;
               ps = s;
               pp = p;
           }
           else if (*s == *p || *p== '?') {
               s++; p++;
           }
           else {
               s = ++ps;
               p = pp;
           }
       }
      
       while(*p == '*') p++;
      
       return !*p;
    }
};

 


// Solution 2 similar to 1 but a little more concise
 bool isMatch( const char *s, const char *p) {
        const char *ps = NULL;
        const char *pp = NULL;
       
        while(*s) {
            if (*p == '*') {
                if (!*++p)  return true;
                ps = s + 1;
                pp = p;
            }
            else if (*s == *p || *p == '?') {
                s++;
                p++;
            }
            else if (ps)
            {
               s = ps++;
               p = pp;
            }
            else return false;
        }
       
        while(*p == '*') p++;
       
        return !*p;
    }

No comments:

Post a Comment