472. Concatenated Words
first thinking, no sort, and put all words into hashset
-> time limit exceeded
class Solution {
public List<String> findAllConcatenatedWordsInADict(String[] words) {
Set<String> wordDict = new HashSet<>();
for (String w : words) {
if (w.length() != 0) {
wordDict.add(w);
}
}
// System.out.println(wordDict.size());
List<String> result = new ArrayList<>();
for (String w : words) {
if (w.length() != 0 && wordBreak(w, wordDict)) {
result.add(w);
}
}
return result;
}
public boolean wordBreak(String s, Set<String> wordDict) {
return dfs(s, 0, wordDict, new Boolean[s.length()]);
}
private boolean dfs(String s, int start, Set<String> wordDict, Boolean[] memo) {
if (start == s.length()) {
return true;
}
if (memo[start] != null) {
return memo[start];
}
for (String w : wordDict) {
if (s.equals(w)) {
continue;
}
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;
}
}
/*
1. use word break thinking
"catsdogcats"
from words ,
if word same to s, skip
if it's true -> add to output
(needs exclude empty string edge case)
*/do sort, shorter one is in front
Last updated
Was this helpful?