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"
.
1 public class Solution { 2 public boolean wordBreak(String s, Set<String> dict) { 3 // Note: The Solution object is instantiated only once and is reused by each test case. 4 if(s == null || s.length() == 0) return true; 5 int len = s.length(); 6 boolean[] map = new boolean[len]; 7 for(int i = len - 1; i > -1; i --){ 8 for(int j = i + 1; j <= len; j ++){ 9 String ss = s.substring(i,j); 10 if(dict.contains(ss) && j == len){ 11 map[i] = true; 12 break; 13 } 14 else if(dict.contains(ss) && j < len && map[j] == true){ 15 map[i] = true; 16 break; 17 } 18 } 19 } 20 return map[0]; 21 } 22 }
第二遍:
1 public class Solution { 2 public boolean wordBreak(String s, Set<String> dict) { 3 // Note: The Solution object is instantiated only once and is reused by each test case. 4 if(s == null || s.length() == 0) return true; 5 int len = s.length(); 6 boolean[] map = new boolean[len]; 7 for(int i = len - 1; i > -1; i --) 8 for(int j = i + 1; j <= len; j ++){ 9 if(j < len && !map[j]) continue; 10 else if(dict.contains(s.substring(i, j)) && (j == len || map[j])){ 11 map[i] = true; 12 break; 13 } 14 } 15 return map[0]; 16 } 17 }
posted on 2013-10-09 11:32 Step-BY-Step 阅读(223) 评论(0) 编辑 收藏 举报