Simple Java solution


  • 0
    P

    Insert, Search and prefix follow pretty much the same pattern.

    class TrieNode {
        TrieNode[] nodes;
        char chr;
        boolean isWordEnd;
        // Initialize your data structure here.
        public TrieNode() {
            nodes = new TrieNode[26];
            chr = '\n';
        }
        public TrieNode(char c) {
            this();
            this.chr = c;
            isWordEnd = false;
        }
    }
    
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        public void insert(String word) {
            if (word == null || word.length() == 0) return;
            TrieNode node = root;
            for(Character chr : word.toCharArray()) {
                if (node.nodes[chr - 'a'] == null) {
                    node.nodes[chr - 'a'] = new TrieNode(chr);
                }
                node = node.nodes[chr - 'a'];
            }
            node.isWordEnd = true;
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            if (word == null || word.length() == 0) return false;
            TrieNode node = root;
            for(Character chr : word.toCharArray()) {
                if (node.nodes[chr - 'a'] == null) return false;
                node = node.nodes[chr - 'a'];
            }
            return node.isWordEnd;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String word) {
            if (word == null || word.length() == 0) return false;
            TrieNode node = root;
            for(Character chr : word.toCharArray()) {
                if (node.nodes[chr - 'a'] == null) return false;
                node = node.nodes[chr - 'a'];
            }
            return true;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.