zoukankan      html  css  js  c++  java
  • 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];
    }
  • 相关阅读:
    idea 2017版破解
    UIRecorder 学习了解
    简单应用单例模式
    线程安全的单例模式(有参and无参)
    批量删除和批量修改(参数使用list)
    简单线程池开启线程
    随机数生成
    网络延迟-tc工具使用简单说明
    c++高级元编程 第一部分,第一节,第一小节
    Writing_Bug_Free_C_Code_Chapter_2_Know_Your_Environment
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5248076.html
Copyright © 2011-2022 走看看