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
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.
Rust Solution
Rust must annotate the collected type — HashSet<&str> — and it holds borrowed &str slices produced by word_dict.iter().map(|w| w.as_str()).collect(), so the set points into word_dict rather than owning fresh copies (unlike JS's untyped new Set(wordDict)). vec![false; n + 1] builds the dp table in one macro, and the inclusive range 1..=n mirrors the dp[i] indexing while 0..i stays exclusive. Membership is word_set.contains(&s[j..i]), where &s[j..i] is a byte-index string slice borrowed straight out of s. The function's final expression dp[n] is the return value, with no return keyword.
Go Solution
Go has no built-in set type, so map[string]bool{} fills that role, populated by for _, w := range wordDict with the blank identifier _ discarding the loop index. make([]bool, len(s)+1) allocates dp already zeroed to false, so unlike JS's .fill(false) only dp[0] needs setting explicitly. Membership is a bare map read — set[s[j:i]] returns the zero value false for an absent key, so the comma-ok v, ok := m[k] form is unnecessary to test presence. s[j:i] slices the string by byte index, and return dp[len(s)] yields the answer.
Comments (0)
Stub — comments live in your browser only (localStorage). No server round-trip yet.
No comments yet. Be the first.