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"
.
1 public class Solution { 2 public boolean wordBreak(String s, Set<String> dict) { 3 int len = s.length(); 4 if(len<=0) return true; 5 boolean p[] = new boolean [len]; 6 for(int i=0;i<len;i++){ 7 if(dict.contains(s.substring(0,i+1))){ 8 p[i] = true; 9 continue; 10 } 11 for(int k=0;k<i;k++){ 12 if(p[k]){ 13 if(dict.contains(s.substring(k+1,i+1))){ 14 p[i]=true; 15 break; 16 } 17 } 18 } 19 } 20 return p[len-1]; 21 } 22 }
原文:http://www.cnblogs.com/krunning/p/3560693.html