Word Break
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
My first solution (Naive Approach)
1 public boolean wordBreak(String s, Set<String> wordDict) { 2 return helper(s, wordDict, 0); 3 } 4 5 public boolean helper(String s, Set<String> wordDict, int pos) { 6 if(pos >= s.length()) 7 return true; 8 9 boolean res = false; 10 for(int i = pos + 1; i <= s.length(); i++) { 11 String sub = s.substring(pos, i); 12 boolean curr = wordDict.contains(sub); 13 if(curr) { 14 curr = helper(s, wordDict, i); 15 } 16 res = res || curr; 17 if(res) return true; 18 } 19 return res; 20 }
Note:
- Line 17 处是需要非常注意的,我们并不需要iterate all possibilities, return true if one possibility works.
- This code is not effient enough, recursion runtime will grow exponentially. As for String length greater than 30, it takes a lot of time to finish.

浙公网安备 33010602011771号