non-recursive java solution


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

Log in to reply
 

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