Created
May 4, 2022 02:16
-
-
Save Rustem/c7b21488131bbc4c4c7c83161b002b77 to your computer and use it in GitHub Desktop.
472. Concatenated Words
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
class TrieNode { | |
int idx; | |
TrieNode[] nodes; | |
public TrieNode() { | |
this.nodes = new TrieNode[26]; | |
this.idx = -1; | |
} | |
public boolean isEndWord() { | |
return this.idx > -1; | |
} | |
} | |
private TrieNode root; | |
public void insertWord(String word, int idx) { | |
if(word.equals("")) | |
return; | |
TrieNode cur = root; | |
for(int i = 0; i<word.length(); i++) { | |
char c = word.charAt(i); | |
if(cur.nodes[c - 'a'] == null) { | |
cur.nodes[c - 'a'] = new TrieNode(); | |
} | |
cur = cur.nodes[c - 'a']; | |
} | |
cur.idx = idx;// if set to be non -1 determines the end of word. | |
} | |
private boolean dfs(String word, TrieNode parent, int wIdx, int origIdx, int depth) { | |
if(wIdx >= word.length()) | |
return false; | |
char c = word.charAt(wIdx); | |
TrieNode cur = parent.nodes[c - 'a']; | |
if(cur == null) | |
return false; | |
if(wIdx == word.length() - 1) { | |
boolean result = cur.isEndWord() && cur.idx != origIdx; | |
return result; | |
} | |
if(cur.isEndWord()) { | |
if(dfs(word, root, wIdx + 1, origIdx, 0)) { | |
return true; | |
} | |
} | |
return dfs(word, cur, wIdx + 1, origIdx, depth + 1); | |
} | |
public List<String> findAllConcatenatedWordsInADict(String[] words) { | |
root = new TrieNode(); | |
int idx = 0; | |
for(String word: words) { | |
insertWord(word, idx); | |
idx ++; | |
} | |
List<String> res = new ArrayList<>(); | |
idx = 0; | |
for(String word: words) { | |
if(dfs(word, root, 0, idx, 0)) { | |
res.add(word); | |
} | |
idx++; | |
} | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment