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