FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithms-python/algorithms/backtrack/pattern_match.py at master · Mu-L/algorithms-python · GitHub
Mu-L
/
algorithms-python
Public
forked from
keon/algorithms
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithms-python
/
algorithms
/
backtrack
/
pattern_match.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
42 lines (34 loc) · 1.29 KB
Breadcrumbs
algorithms-python
/
algorithms
/
backtrack
/
pattern_match.py
Copy path
File metadata and controls
42 lines (34 loc) · 1.29 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""
Given a pattern and a string str,
find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between
a letter in pattern and a non-empty substring in str.
Examples:
pattern = "abab", str = "redblueredblue" should return true.
pattern = "aaaa", str = "asdasdasdasd" should return true.
pattern = "aabb", str = "xyzabcxzyabc" should return false.
Notes:
You may assume both pattern and str contains only lowercase letters.
"""
def
pattern_match
(
pattern
,
string
):
"""
:type pattern: str
:type string: str
:rtype: bool
"""
def
backtrack
(
pattern
,
string
,
dic
):
if
len
(
pattern
)
==
0
and
len
(
string
)
>
0
:
return
False
if
len
(
pattern
)
==
len
(
string
)
==
0
:
return
True
for
end
in
range
(
1
,
len
(
string
)
-
len
(
pattern
)
+
2
):
if
pattern
[
0
]
not
in
dic
and
string
[:
end
]
not
in
dic
.
values
():
dic
[
pattern
[
0
]]
=
string
[:
end
]
if
backtrack
(
pattern
[
1
:],
string
[
end
:],
dic
):
return
True
del
dic
[
pattern
[
0
]]
elif
pattern
[
0
]
in
dic
and
dic
[
pattern
[
0
]]
==
string
[:
end
]:
if
backtrack
(
pattern
[
1
:],
string
[
end
:],
dic
):
return
True
return
False
return
backtrack
(
pattern
,
string
, {})
Back
|
FazBrowse Home
|
New Git URL