|
| 1 | +def matchWordPattern(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 | + >>> matchWordPattern("aba", "GraphTreesGraph") |
| 10 | + True |
| 11 | +
|
| 12 | + >>> matchWordPattern("xyx", "PythonRubyPython") |
| 13 | + True |
| 14 | +
|
| 15 | + >>> matchWordPattern("GG", "PythonJavaPython") |
| 16 | + False |
| 17 | + """ |
| 18 | + def backtrack(pattern_index, str_index): |
| 19 | + if pattern_index == len(pattern) and str_index == len(input_string): |
| 20 | + return True |
| 21 | + if pattern_index == len(pattern) or str_index == len(input_string): |
| 22 | + return False |
| 23 | + |
| 24 | + char = pattern[pattern_index] |
| 25 | + |
| 26 | + if char in pattern_map: |
| 27 | + mapped_str = pattern_map[char] |
| 28 | + if input_string.startswith(mapped_str, str_index): |
| 29 | + return backtrack(pattern_index + 1, str_index + len(mapped_str)) |
| 30 | + else: |
| 31 | + return False |
| 32 | + |
| 33 | + for end in range(str_index + 1, len(input_string) + 1): |
| 34 | + substr = input_string[str_index:end] |
| 35 | + if substr in str_map: |
| 36 | + continue |
| 37 | + |
| 38 | + pattern_map[char] = substr |
| 39 | + str_map[substr] = char |
| 40 | + |
| 41 | + if backtrack(pattern_index + 1, end): |
| 42 | + return True |
| 43 | + |
| 44 | + del pattern_map[char] |
| 45 | + del str_map[substr] |
| 46 | + return False |
| 47 | + |
| 48 | + pattern_map = {} |
| 49 | + str_map = {} |
| 50 | + return backtrack(0, 0) |
| 51 | + |
| 52 | +if __name__ == "__main__": |
| 53 | + import doctest |
| 54 | + doctest.testmod() |
0 commit comments