-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathwildcard_matching.py
58 lines (48 loc) · 1.42 KB
/
wildcard_matching.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#coding: utf-8
''' mbinary
#######################################################################
# File : wildcard_matching.py
# Author: mbinary
# Mail: [email protected]
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2018-12-13 22:46
# Description:
wild card '*' matches 0 or any chars, and '?' matches any single char.
#######################################################################
'''
'''
idea
dynamic programming
dp[m+1][n+1]: bool
i:n, j:m
dp[j][i] indicates if s[:i+1] matches p[:j+1]
initial: dp[0][0] = True, dp[0][i],dp[j][0] = False
only if p startswith '*', dp[1][0] = True.
if p[j] = '*': dp[j][i] = dp[j-1][i] or dp[j][i-1]
elif p[j] = '?': dp[j][i] = dp[j-1][i-1]
else : dp[j][i] = dp[j-1][i-1] and s[i] == p[j]
'''
# leetcode: q44 https://leetcode.com/problems/wildcard-matching/description/
def isMatch(self, s, p):
"""
:type s: str
:type p: str pattern str including wildcard
:rtype: bool
"""
n, m = len(s), len(p)
last = [False]*(n+1)
last[0] = True
for j in range(m):
if p[j] == '*':
for i in range(n):
last[i+1] = last[i+1] or last[i]
elif p[j] == '?':
last.pop()
last.insert(0, False)
else:
li = [False]
for i in range(n):
li.append(last[i] and p[j] == s[i])
last = li
return last[-1]