Word Break Problem: A Dynamic Programming Approach
The "Word Break" problem is a popular question in dynamic programming. It involves determining whether a given string can be segmented into a sequence of one or more dictionary words.
Problem Statement
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Example
-
Input:
s = "leetcode",wordDict = ["leet", "code"]Output:trueExplanation: The string "leetcode" can be segmented as "leet code". -
Input:
s = "applepenapple",wordDict = ["apple", "pen"]Output:trueExplanation: The string can be segmented as "apple pen apple".
Dynamic Programming Solution
function wordBreak(s, wordDict) {
let wordSet = new Set(wordDict);
let dp = new Array(s.length + 1).fill(false);
dp[0] = true;
for (let i = 1; i <= s.length; i++) {
for (let j = 0; j < i; j++) {
if (dp[j] && wordSet.has(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length];
}
Breaking Down the Solution
- Initialize
dpArray: Create an arraydpof lengths.length + 1and initialize all elements tofalse, exceptdp[0], which istrue. - Dynamic Programming Iteration: Iterate through the string
s. For each positioni, check all substrings ending ati. If any substring is found inwordDictand the remaining part of the string up to the start of the substring is also breakable (as indicated bydp), markdp[i]astrue. - Check for Word Break: Return the value of
dp[s.length]. If it'strue, it means the stringscan be segmented into words from the dictionary.
Conclusion
The Word Break problem is an excellent application of dynamic programming to solve string manipulation challenges. It shows how problems can be solved by breaking them down into smaller, more manageable subproblems, and then combining these solutions to solve the larger problem.
Comments (0)
Stub — comments live in your browser only (localStorage). No server round-trip yet.
No comments yet. Be the first.