Helper function that uses backtracking to determine if a valid word segmentation is possible starting from index 'start'. Parameters: input_string (str): The input string to be segmented. word_dict (set[str]): A set of valid dictionary words. start (int): The starting index
(input_string: str, word_dict: set[str], start: int)
| 8 | |
| 9 | |
| 10 | def backtrack(input_string: str, word_dict: set[str], start: int) -> bool: |
| 11 | """ |
| 12 | Helper function that uses backtracking to determine if a valid |
| 13 | word segmentation is possible starting from index 'start'. |
| 14 | |
| 15 | Parameters: |
| 16 | input_string (str): The input string to be segmented. |
| 17 | word_dict (set[str]): A set of valid dictionary words. |
| 18 | start (int): The starting index of the substring to be checked. |
| 19 | |
| 20 | Returns: |
| 21 | bool: True if a valid segmentation is possible, otherwise False. |
| 22 | |
| 23 | Example: |
| 24 | >>> backtrack("leetcode", {"leet", "code"}, 0) |
| 25 | True |
| 26 | |
| 27 | >>> backtrack("applepenapple", {"apple", "pen"}, 0) |
| 28 | True |
| 29 | |
| 30 | >>> backtrack("catsandog", {"cats", "dog", "sand", "and", "cat"}, 0) |
| 31 | False |
| 32 | """ |
| 33 | |
| 34 | # Base case: if the starting index has reached the end of the string |
| 35 | if start == len(input_string): |
| 36 | return True |
| 37 | |
| 38 | # Try every possible substring from 'start' to 'end' |
| 39 | for end in range(start + 1, len(input_string) + 1): |
| 40 | if input_string[start:end] in word_dict and backtrack( |
| 41 | input_string, word_dict, end |
| 42 | ): |
| 43 | return True |
| 44 | |
| 45 | return False |
| 46 | |
| 47 | |
| 48 | def word_break(input_string: str, word_dict: set[str]) -> bool: |