forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregex_match.py
More file actions
Latest commit
97 lines (77 loc) · 2.43 KB
/
Copy pathregex_match.py
File metadata and controls
97 lines (77 loc) · 2.43 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
"""
Regex matching check if a text matches pattern or not.
Pattern:
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
More info:
https://medium.com/trick-the-interviwer/regular-expression-matching-9972eb74c03
"""
defrecursive_match(text: str, pattern: str) ->bool:
"""
Recursive matching algorithm.
Time complexity: O(2 ^ (|text| + |pattern|))
Space complexity: Recursion depth is O(|text| + |pattern|).
:param text: Text to match.
:param pattern: Pattern to match.
:return: True if text matches pattern, False otherwise.
>>> recursive_match('abc', 'a.c')
True
>>> recursive_match('abc', 'af*.c')
True
>>> recursive_match('abc', 'a.c*')
True
>>> recursive_match('abc', 'a.c*d')
False
>>> recursive_match('aa', '.*')
True
"""
ifnotpattern:
returnnottext
ifnottext:
returnpattern[-1] =="*"andrecursive_match(text, pattern[:-2])
iftext[-1] ==pattern[-1] orpattern[-1] ==".":
returnrecursive_match(text[:-1], pattern[:-1])
ifpattern[-1] =="*":
returnrecursive_match(text[:-1], pattern) orrecursive_match(
text, pattern[:-2]
)
returnFalse
defdp_match(text: str, pattern: str) ->bool:
"""
Dynamic programming matching algorithm.
Time complexity: O(|text| * |pattern|)
Space complexity: O(|text| * |pattern|)
:param text: Text to match.
:param pattern: Pattern to match.
:return: True if text matches pattern, False otherwise.
>>> dp_match('abc', 'a.c')
True
>>> dp_match('abc', 'af*.c')
True
>>> dp_match('abc', 'a.c*')
True
>>> dp_match('abc', 'a.c*d')
False
>>> dp_match('aa', '.*')
True
"""
m=len(text)
n=len(pattern)
dp= [[Falsefor_inrange(n+1)] for_inrange(m+1)]
dp[0][0] =True
forjinrange(1, n+1):
dp[0][j] =pattern[j-1] =="*"anddp[0][j-2]
foriinrange(1, m+1):
forjinrange(1, n+1):
ifpattern[j-1] in {".", text[i-1]}:
dp[i][j] =dp[i-1][j-1]
elifpattern[j-1] =="*":
dp[i][j] =dp[i][j-2]
ifpattern[j-2] in {".", text[i-1]}:
dp[i][j] |=dp[i-1][j]
else:
dp[i][j] =False
returndp[m][n]
if__name__=="__main__":
importdoctest
doctest.testmod()