LeetCode-44 Wildcard Matching

Description

Given an input string (s) and a pattern §, 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).

Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like ? or *.

Example

Example 1:
Input:
s = “aa”
p = “a”
Output: false
Explanation: “a” does not match the entire string “aa”.

Example 2:
Input:
s = “aa”
p = ""
Output: true
Explanation: '
’ matches any sequence.

Example 3:
Input:
s = “cb”
p = “?a”
Output: false
Explanation: ‘?’ matches ‘c’, but the second letter is ‘a’, which does not match ‘b’.

Example 4:
Input:
s = “adceb”
p = “ab”
Output: true
Explanation: The first ‘’ matches the empty sequence, while the second '’ matches the substring “dce”.

Example 5:
Input:
s = “acdcb”
p = “a*c?b”
Output: false

Submissions

这道题的解题思路是利用动态规划,建立dp数组l,l[a][b]表示p的前a个字符是否配皮s的前b个字符,所以注意数组的维度是s,p的长度加一。当p[a]== * 时,因为 * 可以匹配任何字符串,所以只需要判断前半部分是否匹配,即l[a][b]=l[a-1][b] 或者 l[a][b]=l[a][b-1 ]。在l[a][b]=l[a-1][b]时( * 表示空串),在l[a][b]=l[a][b-1]时( * 表示任意字符串 ),两者有一个符合即可。当p[a]== ? 或者p[a]==s[b]时,只需要判断p和s的前面部分是否匹配,即l[a][b]=l[a-1][b-1]否则不匹配,l[a][b]=0。

实现代码如下:

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        n = len(s)
        m = len(p)
        l=[]
        for i in range(m+1):
            l.append([0]*(n+1))
        l[0][0]=1
        for a in range(1,m+1):
            if p[a-1]=='*':l[a][0]=l[a-1][0]
            for b in range(1,n+1):
                if p[a-1]=='*':     
                    l[a][b]=l[a-1][b] or l[a][b-1]
                elif p[a-1]=='?'or p[a-1]==s[b-1]:
                    l[a][b]=l[a-1][b-1]
                else:
                    l[a][b]=0
        return l[-1][-1]!=0

参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值