Skip to content

Commit

Permalink
Create concatinate_word_problem.java (#93)
Browse files Browse the repository at this point in the history
* 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
thepremshankarsingh authored Oct 8, 2023
1 parent cb2766c commit a6c49c4
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions Trie/concatinate_word_problem.java
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;
}
}

0 comments on commit a6c49c4

Please sign in to comment.