Skip to main content

Command Palette

Search for a command to run...

Trie in java

Updated
•1 min read•View as Markdown
class Solution {
    class TrieNode {
        TrieNode[] children;
        boolean isEndOfWord;

        public TrieNode() {
            children = new TrieNode[26]; 
            isEndOfWord = false;
        }
    }

    // Trie class
    class Trie {
        private TrieNode root;

        public Trie() {
            root = new TrieNode();
        }

        public void insert(String word) {
            TrieNode node = root;
            for (char c : word.toCharArray()) {
                int index = c - 'a';
                if (node.children[index] == null) {
                    node.children[index] = new TrieNode();
                }
                node = node.children[index];
            }
            node.isEndOfWord = true;
        }

        public String findLongestCommonPrefix() {
            TrieNode node = root;
            String prefix = "";
            while (node != null) {
                int childrenCount = 0;
                int childIndex = -1;
                for (int i = 0; i < 26; i++) {
                    if (node.children[i] != null) {
                        childrenCount++;
                        childIndex = i;
                    }
                }
                if (childrenCount != 1 || node.isEndOfWord) {
                    break;
                }
                prefix += (char) (childIndex + 'a');
                node = node.children[childIndex];
        }
            return prefix;
        }
    }

    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }

        Trie trie = new Trie();
        for (String word : strs) {
            trie.insert(word);
        }

        return trie.findLongestCommonPrefix();
    }
}

More from this blog

codebhghvhv

34 posts