139. Word Break
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
return dfs(s, 0, wordDict, new Boolean[s.length()]);
}
private boolean dfs(String s, int start, List<String> wordDict, Boolean[] memo) {
if (start == s.length()) {
return true;
}
if (memo[start] != null) {
return memo[start];
}
for (String w : wordDict) {
int len = w.length();
if (start + len > s.length()) { // can be s.length() -> in next call, go to base condition
continue;
}
String sub = s.substring(start, start + len);
if (w.equals(sub)) {
if (dfs(s, start + len, wordDict, memo)) {
return memo[start] = true;
}
}
}
return memo[start] = false;
}
}
/*
is s composed from dict?
function (s, wordDict)
for (String w : wordDict ) {
if (s has prefix == w) {
if (dfs(s remove prefix, wordDict)) {
return true
}
}
}
}
*/
Last updated