-
Notifications
You must be signed in to change notification settings - Fork 19
/
answer.py
75 lines (66 loc) · 2.55 KB
/
answer.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/python3
#------------------------------------------------------------------------------
# First Solution
# Not too efficient with all the recursion lol
#------------------------------------------------------------------------------
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
i = 0
for j in range(len(p)):
# If str is longer than pattern -> false
if i > len(s)-1:
# it could potentially be true if the remaining characters are *s
if p[j:].replace("*","") == "":
return True
return False
if p[j] == '?':
# If ?, then increment index
i += 1
elif p[j] == '*':
# If last char in pattern, then true
if j == len(p)-1:
return True
# We want to check all possibilities
for curr in range(i, len(s)):
# If the current char is equal to the next char in the pattern or ?
if s[curr] == p[j+1] or p[j+1] == '?' or p[j+1] == '*':
if self.isMatch(s[curr:], p[j+1:]):
return True
return False
else:
# If any char, check char and increment
if p[j] != s[i]:
return False
i += 1
return i == len(s)
#------------------------------------------------------------------------------
# DP Solution
#------------------------------------------------------------------------------
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
ls = len(s)
lp = len(p)
dp = [[False]*(len(p)+1) for i in range(len(s)+1)]
dp[0][0] = True
for i in range(1,len(p)+1):
if p[i-1] == '*' and dp[0][i-1]:
dp[0][i] = True
for row in range(1, len(s)+1):
for col in range(1, len(p)+1):
if s[row-1] == p[col-1] or p[col-1]=='?':
dp[row][col] = True and dp[row-1][col-1]
elif p[col-1] == '*':
dp[row][col] = dp[row][col-1] or dp[row-1][col-1] or dp[row-1][col]
return dp[len(s)][len(p)]
#------------------------------------------------------------------------------
#Testing