|
| 1 | +""" |
| 2 | +Word Break Problem is a well-known problem in computer science. |
| 3 | +Given a string and a dictionary of words, the task is to determine if |
| 4 | +the string can be segmented into a sequence of one or more dictionary words. |
| 5 | +
|
| 6 | +Wikipedia: https://en.wikipedia.org/wiki/Word_break_problem |
| 7 | +""" |
| 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: |
| 49 | + """ |
| 50 | + Determines if the input string can be segmented into a sequence of |
| 51 | + valid dictionary words using backtracking. |
| 52 | +
|
| 53 | + Parameters: |
| 54 | + input_string (str): The input string to segment. |
| 55 | + word_dict (set[str]): The set of valid words. |
| 56 | +
|
| 57 | + Returns: |
| 58 | + bool: True if the string can be segmented into valid words, otherwise False. |
| 59 | +
|
| 60 | + Example: |
| 61 | + >>> word_break("leetcode", {"leet", "code"}) |
| 62 | + True |
| 63 | +
|
| 64 | + >>> word_break("applepenapple", {"apple", "pen"}) |
| 65 | + True |
| 66 | +
|
| 67 | + >>> word_break("catsandog", {"cats", "dog", "sand", "and", "cat"}) |
| 68 | + False |
| 69 | + """ |
| 70 | + |
| 71 | + return backtrack(input_string, word_dict, 0) |
0 commit comments