- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathmatch_word_pattern.py
61 lines (50 loc) · 1.76 KB
/
match_word_pattern.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
defmatch_word_pattern(pattern: str, input_string: str) ->bool:
"""
Determine if a given pattern matches a string using backtracking.
pattern: The pattern to match.
input_string: The string to match against the pattern.
return: True if the pattern matches the string, False otherwise.
>>> match_word_pattern("aba", "GraphTreesGraph")
True
>>> match_word_pattern("xyx", "PythonRubyPython")
True
>>> match_word_pattern("GG", "PythonJavaPython")
False
"""
defbacktrack(pattern_index: int, str_index: int) ->bool:
"""
>>> backtrack(0, 0)
True
>>> backtrack(0, 1)
True
>>> backtrack(0, 4)
False
"""
ifpattern_index==len(pattern) andstr_index==len(input_string):
returnTrue
ifpattern_index==len(pattern) orstr_index==len(input_string):
returnFalse
char=pattern[pattern_index]
ifcharinpattern_map:
mapped_str=pattern_map[char]
ifinput_string.startswith(mapped_str, str_index):
returnbacktrack(pattern_index+1, str_index+len(mapped_str))
else:
returnFalse
forendinrange(str_index+1, len(input_string) +1):
substr=input_string[str_index:end]
ifsubstrinstr_map:
continue
pattern_map[char] =substr
str_map[substr] =char
ifbacktrack(pattern_index+1, end):
returnTrue
delpattern_map[char]
delstr_map[substr]
returnFalse
pattern_map: dict[str, str] = {}
str_map: dict[str, str] = {}
returnbacktrack(0, 0)
if__name__=="__main__":
importdoctest
doctest.testmod()