Wildcard Matching

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


二维动态规划,类似编辑距离的算法。 首先做一个基本判断(null,空串,模式串的绝对长度大于源串),然后进入两重循环的动态规划, 用源串做列,模式串做行,逐行遍历整个二维空间,每个位置(i,j)都取决于当前模式串字符和源串字符的是否匹配以及上一行和当前行前缀的状态,简单描述如下:
1. 如果p[i]不为'*' ,最简单, 判断p[i]和s[ j - 1]是否相等并且其左上角的状态知否为真(ret[pre][j - 1] == true).
2. 如果p[i]是‘*’, 可以想象,只要上一行从源串偏移 = 1开始到当前j (或者当前行从偏移0开始到j - 1) 有一个为真,则当前行所有位置(ret[cur][j] = true), 大家可以在纸上画一个二维表格看看,想想为什么。



class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (s == NULL || p == NULL) return false;
        if (*p == '\0') return *s == '\0';
        int slen = strlen(s);
        int plen = 0, plen2 = 0;
        for (const char *cp = p; *cp != '\0'; ++cp) {
            ++plen;
            if (*cp != '*') ++plen2;
        }
        
        if (plen2 > slen) return false;
        vector<vector<bool>> ret(2, vector<bool>(slen + 1, false));
        ret[0][0] = true;
        int cur = 1, pre = 0;
        for (int i = 0; i < plen; ++i) {
            ret[cur][0] = (ret[pre][0] && p[i] == '*');
            for (int j = 1; j <= slen; j++) {
                if (p[i] == '*') {
                    while (p[i] == '*') ++i;
                    i--;
                    int k = 0;
                    while (++k <= slen) {
                        if (ret[cur][k] = ret[pre][k] || ret[cur][k - 1]) break;
                    }
                    
                    while (k <= slen) {
                        ret[cur][k++] = true;
                    }
                    break;
                } else {
                    ret[cur][j] = ((s[j - 1] == p[i] || p[i] == '?') && ret[pre][j - 1]);
                }
            }
            swap(pre, cur);
        }
        
        return ret[pre][slen];
    }
};






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值