|
1 |
| -def matchWordPattern(pattern :str, input_string: str) -> bool: |
| 1 | +def match_word_pattern(pattern :str, input_string: str) -> bool: |
2 | 2 | """
|
3 | 3 | Determine if a given pattern matches a string using backtracking.
|
4 | 4 |
|
5 | 5 | pattern: The pattern to match.
|
6 | 6 | input_string: The string to match against the pattern.
|
7 | 7 | return: True if the pattern matches the string, False otherwise.
|
8 | 8 |
|
9 |
| - >>> matchWordPattern("aba", "GraphTreesGraph") |
| 9 | + >>> match_word_pattern("aba", "GraphTreesGraph") |
10 | 10 | True
|
11 | 11 |
|
12 |
| - >>> matchWordPattern("xyx", "PythonRubyPython") |
| 12 | + >>> match_word_pattern("xyx", "PythonRubyPython") |
13 | 13 | True
|
14 | 14 |
|
15 |
| - >>> matchWordPattern("GG", "PythonJavaPython") |
| 15 | + >>> match_word_pattern("GG", "PythonJavaPython") |
16 | 16 | False
|
17 | 17 | """
|
18 | 18 | def backtrack(pattern_index, str_index):
|
19 | 19 | if pattern_index == len(pattern) and str_index == len(input_string):
|
20 | 20 | return True
|
21 | 21 | if pattern_index == len(pattern) or str_index == len(input_string):
|
22 | 22 | return False
|
23 |
| - |
24 | 23 | char = pattern[pattern_index]
|
25 |
| - |
26 | 24 | if char in pattern_map:
|
27 | 25 | mapped_str = pattern_map[char]
|
28 | 26 | if input_string.startswith(mapped_str, str_index):
|
29 | 27 | return backtrack(pattern_index + 1, str_index + len(mapped_str))
|
30 | 28 | else:
|
31 | 29 | return False
|
32 |
| - |
33 | 30 | for end in range(str_index + 1, len(input_string) + 1):
|
34 | 31 | substr = input_string[str_index:end]
|
35 | 32 | if substr in str_map:
|
36 | 33 | continue
|
37 |
| - |
38 | 34 | pattern_map[char] = substr
|
39 | 35 | str_map[substr] = char
|
40 |
| - |
41 | 36 | if backtrack(pattern_index + 1, end):
|
42 | 37 | return True
|
43 |
| - |
44 | 38 | del pattern_map[char]
|
45 | 39 | del str_map[substr]
|
46 | 40 | return False
|
47 |
| - |
48 | 41 | pattern_map = {}
|
49 | 42 | str_map = {}
|
50 | 43 | return backtrack(0, 0)
|
|
0 commit comments