• 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];
    }
  • 相关阅读:
    2014华为员工年终奖及年薪盘点
    Gradle命令行黑魔法
    委托的那些事
    动态代理
    音乐播放
    Eclipse plugin web site 发布和版本更新
    JavaScript—之对象参数的引用传递
    Bootstrap 3 How-To #1 下载与配置
    代码审计和漏洞挖掘的思路
    核心C#
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5248076.html
Copyright © 2020-2023  润新知