LeetCode-- 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

思路:动态规划法。
类似于Regular Expression Matching的写法,但是又有不同。
外卡匹配和正则匹配最大的区别就是星号的使用规则,正则匹配中星号不能单独存在,前面必须要有一个字符,而星号存在的意义就是表示前面那个字符的个数可以是任意个数,包括0个,也就是说可以是一个新的字符,只要个数是0就行,后面匹配就好。而外卡匹配就不是这样子,它的星号和前面的字符无关,如果前面的字符没有匹配就不行了。而星号存在的作用是可以表示任意的字符串,比如匹配字符串没有的字符都可以用星号代替,但是匹配字符串多出来的目标字符串没有的部分就不行了。
如果s[0..i]和p[0..j]匹配,则状态dp[i][j]为ture,反之为false。状态方程如下:
if p[j - 1] ==‘*’
dp[i][j] = dp[i - 1][j]||dp[i][j-1],
if p[j - 1] != ‘*’
dp[i][j] = dp[i-1][j - 1]&&(s[i-1]==p[j-1]||p[j-1]==’?’),

class Solution {
public:
    bool isMatch(string s, string p) {
        int m=s.size(),n=p.size();
        vector<vector<bool>>dp(m+1,vector<bool>(n+1,false));
        dp[0][0]=true;
        for(int i=1;i<=n;i++){
            if(p[i-1]=='*'){
                dp[0][i]=dp[0][i-1];
            }
        }
        for(int i=1;i<=m;i++){
            for(int j=1;j<=n;j++){
                if(p[j-1]=='*'){
                    dp[i][j]=dp[i-1][j]||dp[i][j-1];
                }
                else{
                    dp[i][j]=(s[i-1]==p[j-1]||p[j-1]=='?')&&dp[i-1][j-1];   
                }
            }
        }
        return dp[m][n];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值