Share my java solution


  • 0
    G
    class TrieNode {
        // Initialize your data structure here.
        HashMap<Character, TrieNode> map = new HashMap<Character, TrieNode>();
        boolean end = false;
        public TrieNode() {
        }
    }
    
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        public void insert(String word) {
            TrieNode searchNode = root;
            for (char c : word.toCharArray()) {
                if (searchNode.map.containsKey(c)) {
                    searchNode = searchNode.map.get(c);
                }
                else {
                    TrieNode node = new TrieNode();
                    searchNode.map.put(c, node);
                    searchNode = node;
                }
            }
            searchNode.end = true;
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            TrieNode searchNode = root;
            for (char c : word.toCharArray()) {
                if (searchNode.map.containsKey(c)) {
                    searchNode = searchNode.map.get(c);
                }
                else {
                    return false;
                }
            }
            if (searchNode.end) {
                return true;
            }
            return false;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            TrieNode searchNode = root;
            for (char c : prefix.toCharArray()) {
                if (searchNode.map.containsKey(c)) {
                    searchNode = searchNode.map.get(c);
                }
                else {
                    return false;
                }
            }
            return true;
        }
    }

Log in to reply
 

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