DFS+Memo
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> dict = new HashSet<>(wordDict);
Map<String, Boolean> memo = new HashMap<>();
return dfs(s, dict, memo);
}
private boolean dfs(String s, Set<String> dict, Map<String, Boolean> memo) {
if (dict.contains(s)) {
return true;
}
if (memo.containsKey(s)) {
return memo.get(s);
}
for (int i = 0; i < s.length(); i++) {
String substring = s.substring(0, i);
if (dict.contains(substring) && dfs(s.substring(i), dict, memo)) {
memo.put(s, true);
return true;
}
}
memo.put(s, false);
return false;
}Last updated
Was this helpful?