Accept solution using hashmap


  • 0
    S
    class TrieNode {
    	List<TrieNode> next;
    	// Initialize your data structure here.
    	public TrieNode() {
    		next = new ArrayList<TrieNode>();
    	}
    }
    
    public class Trie {
    	private TrieNode root;
    	private Map<String, TrieNode> map;
    
    	public Trie() {
    		root = new TrieNode();
    		map = new HashMap<>();
    		map.put("", root);
    	}
    
    	// Inserts a word into the trie.
    	public void insert(String word) {
    		TrieNode pre = null;
    		for (int i = word.length(); i >= 0; i--) {
    			String sub = word.substring(0, i);
    			if (!map.containsKey(sub)){
    				map.put(sub, new TrieNode());
    				map.get(sub).next.add(pre);
    				pre = map.get(sub);
    			}else {
    				map.get(sub).next.add(pre);
    				return;
    			}
    		}
    	}
    
    	// Returns if the word is in the trie.
    	public boolean search(String word) {
    		return map.containsKey(word) ? map.get(word).next.contains(null) : false;
    	}
    
    	// Returns if there is any word in the trie
    	// that starts with the given prefix.
    	public boolean startsWith(String prefix) {
    		return map.containsKey(prefix);
    	}
    }
    

Log in to reply
 

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