dynamic programming
1 public class Solution { 2 public boolean wordBreak(String s, Set<String> dict) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 if(s == null||dict.isEmpty()) 6 return false; 7 int length = s.length(); 8 boolean[][] seg = new boolean[length][length + 1]; 9 for(int len = 1; len <= length; len++){ 10 for(int i = 0; i < length; i++){ 11 int tmp = i + len; 12 if(i+len > length) 13 tmp = length; 14 String t = s.substring(i, tmp); 15 if(dict.contains(t)){ 16 seg[i][len] = true; 17 continue; 18 } 19 for(int k = 1; k < len; k++){ 20 if(seg[i][k] && seg[i+k][len-k]){ 21 seg[i][len] = true; 22 break; 23 } 24 } 25 } 26 } 27 return seg[0][length]; 28 29 } 30 }