Word Break

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.

Note:

The same word in the dictionary may be reused multiple times in the segmentation. You may assume the dictionary does not contain duplicate words.

Example 1:

Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2:

Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
             Note that you are allowed to reuse a dictionary word.

Example 3:

Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false

Analysis

不是一般的DP,在这类有 Word Dict的题目时,容易想到用Trie来存,但是并不一定能够带来算法效率的提升。

dp[i] 来表示从0到i, 即[0, 1),左闭右开区间,是否满足可以分解成的词都来自字典。

状态转移方程:dp[i] = dp[j] && wordDict.contains(s.substring(j, i))

起始条件:dp[0] = true;

答案:dp[s.length()]

Solution

DP - O(n) space, O(n^2) - (14ms, 18.91% AC)

DP - without converting list to set (7ms, 74.94% AC)

DP - Optimize with Max Length constraint (2ms, 100%)

Another DP Solution

Reference

https://leetcode.com/problems/word-break/discuss/43886/Evolve-from-brute-force-to-optimal-a-review-of-all-solutions

https://leetcode.com/problems/word-break/discuss/43790/Java-implementation-using-DP-in-two-ways

Last updated

Was this helpful?