[Leetcode] Wildcard Matching

Wildcard MatchingMar 16 '127489 / 29783

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

第一个方法是ok的,采用的dp。

dp[i][j] = 1 表示s[1~i] 和 p[1~j] match。

则:

if p[j] == '*' && (dp[i][j-1] || dp[i-1][j]) 

dp[i][j] =  1 

else p[j] = ? || p[j] == s[i]

dp[i][j] = dp[i-1][j-1];

else dp[i][j] = false;

第二个方法:TLE

相比于dp,暴力的方法会多次计算dp[i][j].

其实如果要优化的话,也是非常容易的。只需要记录下 (s,p)是否处理过。

class Solution {
public:

    bool isMatch(const char *s, const char *p) {
        int len_s = strlen(s);
        int len_p = strlen(p);

        const char* tmp = p;
        int cnt = 0;
        while (*tmp != '\0') if (*(tmp++) != '*') cnt++;
        if (cnt > len_s) return false;
        
        bool dp[500][500];
        memset(dp, 0,sizeof(dp));

        dp[0][0] = true;
        for (int i = 1; i <= len_p; i++) {
            if (dp[0][i-1] && p[i-1] == '*') dp[0][i] = true;
            for (int j = 1; j <= len_s; ++j)
            {
                if (p[i-1] == '*') dp[j][i] = (dp[j-1][i] || dp[j][i-1]);
                else if (p[i-1] == '?' || p[i-1] == s[j-1]) dp[j][i] = dp[j-1][i-1];
                else dp[j][i] = false;
            }
        }
        return dp[len_s][len_p];
    }
};


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

猜你喜欢

转载自cozilla.iteye.com/blog/1929109