Skip to content

Commit 4f0baa2

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent 5442a69 commit 4f0baa2

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

Diff for: backtracking/match_word_pattern.py

+11-8
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
def matchWordPattern(pattern :str, input_string: str) -> bool:
1+
def matchWordPattern(pattern: str, input_string: str) -> bool:
22
"""
33
Determine if a given pattern matches a string using backtracking.
44
@@ -15,40 +15,43 @@ def matchWordPattern(pattern :str, input_string: str) -> bool:
1515
>>> matchWordPattern("GG", "PythonJavaPython")
1616
False
1717
"""
18+
1819
def backtrack(pattern_index, str_index):
1920
if pattern_index == len(pattern) and str_index == len(input_string):
2021
return True
2122
if pattern_index == len(pattern) or str_index == len(input_string):
2223
return False
23-
24+
2425
char = pattern[pattern_index]
25-
26+
2627
if char in pattern_map:
2728
mapped_str = pattern_map[char]
2829
if input_string.startswith(mapped_str, str_index):
2930
return backtrack(pattern_index + 1, str_index + len(mapped_str))
3031
else:
3132
return False
32-
33+
3334
for end in range(str_index + 1, len(input_string) + 1):
3435
substr = input_string[str_index:end]
3536
if substr in str_map:
3637
continue
37-
38+
3839
pattern_map[char] = substr
3940
str_map[substr] = char
40-
41+
4142
if backtrack(pattern_index + 1, end):
4243
return True
43-
44+
4445
del pattern_map[char]
4546
del str_map[substr]
4647
return False
47-
48+
4849
pattern_map = {}
4950
str_map = {}
5051
return backtrack(0, 0)
5152

53+
5254
if __name__ == "__main__":
5355
import doctest
56+
5457
doctest.testmod()

0 commit comments

Comments
 (0)