zoukankan      html  css  js  c++  java
  • 208. Implement Trie (Prefix Tree)

    Implement a trie with insertsearch, and startsWith methods.

    Note:
    You may assume that all inputs are consist of lowercase letters a-z.

    Show Company Tags
    Show Tags
    Show Similar Problems
     
    class TrieNode {
        // Initialize your data structure here.
        HashMap<Character, TrieNode> map;
        boolean isWord;
        
        public TrieNode() {
            map = new HashMap<Character, TrieNode>();
            isWord = false;
        }
    }
    
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        public void insert(String word) {
            TrieNode it = root;
            for(char c : word.toCharArray()){
                if(!it.map.containsKey(c)){
                    it.map.put(c , new TrieNode() );
                }
                it = it.map.get(c);
            }
            it.isWord = true;
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            TrieNode it = root;
            for(char c : word.toCharArray()){
                if(!it.map.containsKey(c)){
                    return false;
                }
                it = it.map.get(c);
            }
            return it.isWord;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            TrieNode it = root;
            for(char c : prefix.toCharArray()){
                if(!it.map.containsKey(c)){
                    return false;
                }
                it = it.map.get(c);
            }
            return true;
        }
    }
    
    // Your Trie object will be instantiated and called as such:
    // Trie trie = new Trie();
    // trie.insert("somestring");
    // trie.search("key");
  • 相关阅读:
    Entity Framework Core系列教程-1-介绍
    火锅大队作品简介
    一号课题组作品简介
    Attract队作品简介
    华理时空之眼队作品简介
    热情致终队作品简介
    触摸阳光队作品简介
    PIE SDK水体指数法
    PIE SDK水深提取算法
    PIE SDK直方图统计法
  • 原文地址:https://www.cnblogs.com/joannacode/p/6130335.html
Copyright © 2011-2022 走看看