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