LeetCode: 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

递归解法,会TLE。

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (*s == '\0')
        {
            if (*p == '\0')
                return true;
            else if (*p == '*')
            {
                do
                {
                    ++p;
                }while(*p == '*');
                return !(*p);
            }
            else
                return false;
        }
        else
        {
            if (*p == '\0')
                return false;
            else if('?' == *p || *p == *s)
            {
                return isMatch(s+1, p+1);
            }
            else if('*' == *p)
                return isMatch(s, p+1) || isMatch(s+1, p);
            else
                return false;
        }
    }
};

非递归:80ms

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        const char *str, *pat;
        bool star = false;
        
        for (str = s, pat = p; *str != '\0'; ++str, ++pat)
        {
            switch(*pat)
            {
                // 遇到'?',那么不管*str是任何字母都能匹配
                case '?':
                    break;
                case '*':
                    star = true;
                    // 暂时忽略‘*’
                    s = str, p = pat;
                    do
                    {
                        ++p;
                    }while(*p == '*');
                     // 如果'*'之后,pat是空的,直接返回true
                    if (!*p)
                        return true;
                    // 重新开始匹配
                    str = s - 1;
                    pat = p - 1;
                    break;
                default:
                    if (*str != *pat)
                    {
                        // 如果前面没有'*',则匹配不成功
                        if (!star)
                            return false;
                        // 从s的下一位和'*'之后的p重新开始匹配
                        ++s;
                        str = s - 1;
                        pat = p - 1;
                    }
                    break;
            }
        }
        
        while (*pat == '*')
            ++pat;
        return (!*pat);
    }
};

点赞