LeetCode #139: Word Break
https://leetcode.com/problems/word-break/
To solve this problem, we can use a backtracking approach that checks all possible combinations of substrings that exist in the dictionary. We can use a recursive function that takes the index of the current character we are examining and a list that represents the current path we have taken to get to this point.
Here are the steps to solve the problem:
- Create a result list to store all the possible combinations of substrings that exist in the dictionary.
- Define a recursive function called backtrack that takes the index of the current character we are examining and a list that represents the current path we have taken to get to this point.
- Base case: If the index is equal to the length of the string, then we have found a valid combination of substrings. Append the current path to the result list.
- For each word in the dictionary, check if it matches the substring starting from the current index. If it does, append the word to the current path and call the backtrack function recursively with the index updated to the end of the current word.
- If none of the words in the dictionary match the current substring, return.
- Finally, iterate through the result list and check if any of the combinations match the input string.
Here’s the solution in Python:
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
res = []
@lru_cache(list)
def backtrack(ind, path):
if ind == len(s):
res.append("".join(path))
return
for w in wordDict:
if s.startswith(w, ind):
path.append(w)
backtrack(ind+len(w), path)
path.pop()
backtrack(0, [])
for i in res:
if i == s:
return True
return False
Time and Space Complexity
The time complexity of this solution is O(n^2), where n is the length of the input string. This is because we are using a nested loop to check if each substring is in the dictionary. The space complexity is also O(n^2) because we are using memoization to cache the results of previous function calls.