44. Wildcard Matching *HARD*

Posted ArgenBarbie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了44. Wildcard Matching *HARD*相关的知识,希望对你有一定的参考价值。

‘?‘ 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

1. 动态规划
bool isMatch(string s, string p) {
    int ls = s.length(), lp = p.length(), i, j;
    vector<vector<bool>> dp(2, vector<bool>(lp+1, 0));
    bool k = 1;
    dp[0][0] = 1;
    for(i = 1; i <= lp; i++)
        dp[0][i] = dp[0][i-1] && * == p[i-1];
    for(i = 1; i <= ls; i++)
    {
        dp[k][0] = 0;
        for(j = 1; j <= lp; j++)
        {
            if(* == p[j-1])
                dp[k][j] = dp[k][j-1] || dp[!k][j];
            else
                dp[k][j] = dp[!k][j-1] && (p[j-1] == s[i-1] || ? == p[j-1]);
        }
        k = !k;
    }
    return dp[!k][lp];
}

 2. 不匹配的时候回到上一个星号的地方,使星号多匹配一个字符。

bool isMatch(string s, string p) {
    int ls = s.length(), lp = p.length(), last_i = -1, last_j = -1, i = 0, j = 0;
    while(s[i])
    {
        if(* == p[j])
        {
            j++;
            if(!p[j])
                return 1;
            last_i = i;
            last_j = j;
        }
        else if(s[i] == p[j] || ? == p[j])
        {
            i++;
            j++;
        }
        else if(last_i != -1)
        {
            i = ++last_i;
            j = last_j;
        }
        else
            return 0;
    }
    while(* == p[j])
        j++;
    return !p[j];
}

 

以上是关于44. Wildcard Matching *HARD*的主要内容,如果未能解决你的问题,请参考以下文章

44. Wildcard Matching

44. Wildcard Matching(js)

leetcode 44. Wildcard Matching

Leetcode 44: Wildcard Matching

Leetcode 44: Wildcard Matching

LeetCode-44-Wildcard Matching