-
Notifications
You must be signed in to change notification settings - Fork 29
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create concatinate_word_problem.java (#93)
* Create concatinate_word_problem.java Hacktober'23 Added a trie problem * Update concatinate_word_problem.java Problem link added as comment in the file
- Loading branch information
1 parent
cb2766c
commit a6c49c4
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
//Problem Link: https://leetcode.com/problems/concatenated-words/description/ | ||
package Trie; | ||
|
||
class concatinate_word_problem { | ||
class Trie{ | ||
Trie[] children; | ||
boolean isWord; | ||
|
||
public Trie(){ | ||
children = new Trie[26]; | ||
isWord = false; | ||
} | ||
} | ||
Trie root = new Trie(); | ||
|
||
private void buildTrie(String word){ | ||
Trie trie = root; | ||
|
||
for(char c : word.toCharArray()){ | ||
if(trie.children[c-'a'] == null){ | ||
trie.children[c-'a'] = new Trie(); | ||
} | ||
trie = trie.children[c-'a']; | ||
} | ||
trie.isWord = true; | ||
} | ||
|
||
private boolean searchWord(String words, int count){ | ||
Trie node = root; | ||
for(int i=0; i< words.length(); i++){ | ||
char c = words.charAt(i); | ||
if(node.children[c-'a'] == null) return false; | ||
node = node.children[c-'a']; | ||
if(node.isWord && searchWord(words.substring(i+1),count+1)) return true; | ||
} | ||
count++; | ||
return (count >1 && node.isWord) ? true : false; | ||
} | ||
public List<String> findAllConcatenatedWordsInADict(String[] words) { | ||
Arrays.sort(words, (a,b)-> a.length()-b.length()); | ||
ArrayList<String> result = new ArrayList<>(); | ||
|
||
for(String word : words){ | ||
if(searchWord(word, 0)){ | ||
result.add(word); | ||
} | ||
else buildTrie(word); | ||
} | ||
return result; | ||
} | ||
} |