From a6c49c4ebe074b1702711b32d6347591258729ee Mon Sep 17 00:00:00 2001 From: thepremshankarsingh <146573212+thepremshankarsingh@users.noreply.github.com> Date: Sun, 8 Oct 2023 17:05:07 +0530 Subject: [PATCH] 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 --- Trie/concatinate_word_problem.java | 51 ++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Trie/concatinate_word_problem.java diff --git a/Trie/concatinate_word_problem.java b/Trie/concatinate_word_problem.java new file mode 100644 index 0000000..072f7b3 --- /dev/null +++ b/Trie/concatinate_word_problem.java @@ -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 findAllConcatenatedWordsInADict(String[] words) { + Arrays.sort(words, (a,b)-> a.length()-b.length()); + ArrayList result = new ArrayList<>(); + + for(String word : words){ + if(searchWord(word, 0)){ + result.add(word); + } + else buildTrie(word); + } + return result; + } +}