Wednesday, July 23, 2014

[LeetCode] Wildcard Matching

Problem Statement (link):
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
Analysis:
The difficulty of this problem is how to deal with '*' as it may match None or 1 or more chars.

Suppose we use a variable to record the position of '*' in string p, and we temporarily skip to the next non-'*' char. If that char in string p matches a char in string s, life is good - meaning that we could match the '*' with either None or multiple chars in string s; otherwise, we proceed the pointer in string s to seek for a matching char.

An example worth a million words. Suppose we have:

s="abcde", p="?**e*"

- compare 'a' with '?' ==> match, advance both pointers s & p
- see a '*', use variable star to record the star location, advance p, use variable ss to record s's pointer
- see another '*', update both p and star. Now s-->'b', p-->'e'
- variable star is not empty, advance both p and ss (and s), until we meet 'e' in string s
- 'e' matches 'e', advance both pointers, and now *s=='\0', we jump out of the while loop
- Finally, skip all left '*'s from string p. If we reach end of string p, return true; otherwise, return false;

Code:
class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        const char *star=NULL, *ss=s;
        while(*s!='\0') {
            if (*s==*p || *p=='?') {
                s++; p++; continue;
            }
            if (*p=='*') {
                star=p++; ss=s; continue;
            }
            if (star) {
                p=star+1; s=++ss; continue;
            }
            return false;
        }
        while (*p=='*') p++;
        return *p=='\0';
    }
};



No comments:

Post a Comment