Welcome to our deep dive into the fascinating world of Data Structures and Algorithms! Today, we'll explore two captivating problems known as Word Break I and II. These problems are not only fun to solve but also highly relevant in real-world programming projects.
šÆ Objective: Given a string s and a list of words wordList, determine if it's possible to break s into a space-separated sequence of words from wordList.
result. This will store our final solution.s. For each character, find the longest word from wordList that ends at the current index. If a word is found, add it to result and move the index to the next character.False. If all characters have been processed, and result is not empty, return True.š” Pro Tip: Use a dictionary to store the indices of words in wordList. This will help us find the longest word ending at a particular index faster.
def word_break(s, wordList):
# Store indices of words in a dictionary for faster lookups
word_dict = {word: i for i, word in enumerate(wordList)}
result = []
index = 0
while index < len(s):
word = s[index:]
if word in word_dict and word_dict[word] > index:
result.append(word_dict[word])
index += word_dict[word]
else:
break
# If the solution is empty, the string can't be broken
if not result:
return False
# Ensure the last word is valid and the remaining string is empty
last_word = result.pop()
if last_word + s[last_word:] in word_dict:
return True
else:
return FalsešÆ Objective: Given a string s and a list of words wordList, find all possible ways to break s into a space-separated sequence of words from wordList.
word_break function from the previous problem to return a list of possible solutions instead of a boolean value.wordList.š” Pro Tip: Use a dictionary to store the indices of words in a reverse order to make it easier to explore words from the right end of the string.
from typing import List
def word_break(s, wordList):
# Store indices of words in a dictionary for faster lookups
word_dict = {word: i for i, word in enumerate(wordList, 1)}
def find_solutions(remaining_s, remaining_words, solutions):
if not remaining_s:
solutions.append(remaining_words)
return
for word in remaining_words:
if word <= len(remaining_s) and remaning_s[:word] in word_dict:
find_solutions(remaining_s[word:], remaining_words[word:], solutions)
find_solutions(s, wordList, [])
return solutionsWhat is the main goal of the Word Break I problem?
Now that you've learned about Word Break I and II, try solving these problems with different input strings and word lists. Happy coding! š