标签:
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
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:
标签:
原文地址:http://www.cnblogs.com/alanluan/p/4579904.html