# Leetcode 44：通配符匹配（超详细的解法！！！）

'?' 可以匹配任何单个字符。
'*' 可以匹配任意字符串（包括空字符串）。


• s 可能为空，且只包含从 a-z 的小写字母。
• p 可能为空，且只包含从 a-z 的小写字母，以及字符 ?*

输入:
s = "aa"
p = "a"



输入:
s = "aa"
p = "*"



输入:
s = "cb"
p = "?a"



输入:
p = "*a*b"



输入:
s = "acdcb"
p = "a*c?b"



• $f(i,j)=f(i,j-1)\ or\ f(i-1, j)\ \ if\ \ p[j-1]='*'$
• $f(i,j)=f(i-1,j-1)\ \ and \ \ (s[i-1]==p[j-1] || p[j-1]=='?')\ \ if\ \ p[j-1]\neq'*'$

f(i,j)表示输入s[0:i]和输入p[0:j]时的匹配结果。具体的思维转换过程可以阅读之前的文章。

class Solution:
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
s_len, p_len = len(s), len(p)
mem = [[False]*(p_len + 1) for _ in range(s_len + 1)]
mem[0][0] = True
for i in range(s_len + 1):
for j in range(1, p_len + 1):
if p[j-1] == '*':
mem[i][j] = mem[i][j-1] or \
(i > 0 and mem[i-1][j])
else:
mem[i][j] = i > 0 and\
mem[i-1][j-1] and \
(s[i-1] == p[j-1] or p[j-1] == "?")

return mem[-1][-1]


s: a d c e b
i
p: * a * b
j


s: a d c e b
i
p: * a * b
j
star:0
i_index:0


s: a d c e b
i
p: * a * b
j
star:0
i_index:0


s: a d c e b
i
p: * a * b
j
star:2
i_index:1


s: a d c e b
i
p: * a * b
j
star:2
i_index:1


s: a d c e b
i
p: * a * b
j
star:2
i_index:1


class Solution:
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
s_len, p_len = len(s), len(p)
i, j, star, i_index = 0, 0, -1, 0
while i < s_len:
if j < p_len and (p[j] == '?' or p[j] == s[i]):
i += 1
j += 1
elif j < p_len and p[j] == '*':
star = j
j += 1
i_index = i
elif star != -1:
j = star + 1
i_index += 1
i = i_index
else:
return False

while j < p_len and p[j] == '*':
j += 1

return j == p_len


reference:

https://leetcode.com/problems/wildcard-matching/discuss/17810/Linear-runtime-and-constant-space-solution