Question
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
Solution
采用动态规划(DP)
- 使用dp动态规划来处理,将问题拆分有关联的子问题
- 例如dp[i]表示s[:i]是否可以被分词且都在字典数组中
- 在 dp[j] == 1, j>=0, j<i 的情况下,只要满足s[j:i]出现在字典数组中,则 dp[i] = 1 是成立的
- 所以需要处理下第一个边界,后面就可以用上述公式来推算出来
Runtime: 3 ms, faster than 97.51% of Java online submissions for Word Break.
Memory Usage: 36.8 MB, less than 69.21% of Java online submissions for Word Break.
1 | class Solution { |