原题链接在这里:https://leetcode.com/problems/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
题解:
Let dp[i] denotes up to index i, s.substring(0,i) could break into words or not.
For all the j from 0 to i, if dp[j] is true, and s.substring(j,i) is in the dictionary, then dp[i] is true.
Time Complexity: O(s.length() ^ 3). since after Java 7, substring take O(n).
Space: O(s.length()).
AC Java:
1 class Solution { 2 public boolean wordBreak(String s, List<String> wordDict) { 3 if(s == null || s.length() == 0){ 4 return true; 5 } 6 7 HashSet<String> hs = new HashSet<String>(wordDict); 8 boolean [] dp = new boolean[s.length()+1]; 9 dp[0] = true; 10 for(int i = 0; i<=s.length(); i++){ 11 for(int j = 0; j<i; j++){ 12 if(dp[j] && hs.contains(s.substring(j, i))){ 13 dp[i] = true; 14 continue; 15 } 16 } 17 } 18 19 return dp[s.length()]; 20 } 21 }
这题后面还有一个进阶版本的Word Break II.