码迷,mamicode.com
首页 > 其他好文 > 详细

44. Wildcard Matching *HARD*

时间:2016-03-06 18:58:01      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/argenbarbie/p/5248076.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!