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"
.
public class Solution { public boolean wordBreakHelper(String s,Set<String> dict,HashMap<String,Boolean> ht){ if (s.length()<1){ return true; } boolean flag = false; for(int i=0;i<=s.length();i++){ String temp = s.substring(0,i); if (dict.contains(temp)){ if (ht.get(s.substring(temp.length(),s.length()))!=null){ flag = ht.get(s.substring(temp.length(),s.length())); }else{ flag = wordBreakHelper(s.substring(temp.length(), s.length()), dict, ht); ht.put(s.substring(temp.length(),s.length()),flag); } } if (flag) { return true; } } return false; } public boolean wordBreak(String s, Set<String> dict) { return wordBreakHelper(s, dict, new HashMap<String, Boolean>()); } }