Skip to content

Commit c1680ba

Browse files
committed
fix: issue TheAlgorithms#9844
1 parent 5442a69 commit c1680ba

File tree

1 file changed

+4
-11
lines changed

1 file changed

+4
-11
lines changed

Diff for: backtracking/match_word_pattern.py

+4-11
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,43 @@
1-
def matchWordPattern(pattern :str, input_string: str) -> bool:
1+
def match_word_pattern(pattern :str, input_string: str) -> bool:
22
"""
33
Determine if a given pattern matches a string using backtracking.
44
55
pattern: The pattern to match.
66
input_string: The string to match against the pattern.
77
return: True if the pattern matches the string, False otherwise.
88
9-
>>> matchWordPattern("aba", "GraphTreesGraph")
9+
>>> match_word_pattern("aba", "GraphTreesGraph")
1010
True
1111
12-
>>> matchWordPattern("xyx", "PythonRubyPython")
12+
>>> match_word_pattern("xyx", "PythonRubyPython")
1313
True
1414
15-
>>> matchWordPattern("GG", "PythonJavaPython")
15+
>>> match_word_pattern("GG", "PythonJavaPython")
1616
False
1717
"""
1818
def backtrack(pattern_index, str_index):
1919
if pattern_index == len(pattern) and str_index == len(input_string):
2020
return True
2121
if pattern_index == len(pattern) or str_index == len(input_string):
2222
return False
23-
2423
char = pattern[pattern_index]
25-
2624
if char in pattern_map:
2725
mapped_str = pattern_map[char]
2826
if input_string.startswith(mapped_str, str_index):
2927
return backtrack(pattern_index + 1, str_index + len(mapped_str))
3028
else:
3129
return False
32-
3330
for end in range(str_index + 1, len(input_string) + 1):
3431
substr = input_string[str_index:end]
3532
if substr in str_map:
3633
continue
37-
3834
pattern_map[char] = substr
3935
str_map[substr] = char
40-
4136
if backtrack(pattern_index + 1, end):
4237
return True
43-
4438
del pattern_map[char]
4539
del str_map[substr]
4640
return False
47-
4841
pattern_map = {}
4942
str_map = {}
5043
return backtrack(0, 0)

0 commit comments

Comments
 (0)