题目描述
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”.
解题
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
HashMap<String,Boolean> findString=new HashMap<>();
return dfs(s,findString,dict);
}
public boolean dfs(String s,HashMap<String,Boolean> hashMap,Set<String> dict){
if (hashMap.containsKey(s)) return hashMap.get(s);
if (s.equals("")){
return true;
}
boolean find=false;
int len=s.length();
for (int i=1;i<=len;i++){
String header=s.substring(0,i);
if (dict.contains(header)){
boolean child=dfs(s.substring(i,s.length()),hashMap,dict);
if (child==true){
find=true;
break;
}
}
}
hashMap.put(s,find);
return find;
}
}