Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Written by Array Alchemist
LeetCode wizard with 75 conquered challenges under my belt.
Turning algorithm nightmares into "Aha!" moments, one explanation at a time.
Join me to level up your coding skills – from interviews to real-world application!
First let's understand why this problem is important to understand?
and that we know the technique to solve it.
Scenario:
You're a codebreaker for the Allied forces during World War II. The enemy is sending encrypted messages without spaces between words. Your team has intercepted a list of common words the enemy uses in their communications. Your mission is to determine if an intercepted message can be deciphered using the known word list.
Problem: Given an intercepted message (a string without spaces) and a list of known enemy words, determine if the message can be completely broken down into words from the list.
Success case:
Failure case:
Some other application of word break problems are:
Now, that we know why this is important?
let's see how we can solve it?
we are give
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Example 2:
Example 3:
from the examples we can conclude :
pseduocode
var wordBreak = function(s, wordDict) { for(i iterate over s){ for(let word of wordDict){ // check if the word.length < i so that still are valid // const newWords = s.substring( using i & word.length) // prevWord =s.substring(from prev cycle) was in wordDict // also make sure prevWord was a word in the wordDict if(newWord === word & prevWord){ store result = true } } } }here while computing:
function finalRevision(s, wordDict){ // to store the result const dp = new Array(s.length + 1).fill(false) // intializing the 1st element to true to build the result dp[0] = true for(let i = 0; i <= s.length; i++){ for(word of wordDict){ if(word.length <= i){ // form a word const start = i - word.length const newword = s.substring(start, i) // if prevWord was valid && new word is valid if(dp[start] && newword === word){ dp[i] = true } } } } /* this last index will be true if prev was true prev will be true if prev of prev was true prev of Prev will be true if prev of prev of prev was true thus sending the last index of array. */ return dp[s.length] }key note: in pretty much all of the comparison we have <=