• 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");
  • 相关阅读:
    在CentOS 8上安装Jitsi Meet
    centos8 安装docker
    [git]error: pack-objects died of signal
    Andorid 11调用系统裁剪
    XCode修改工程名(完美版)
    java分割后台日志
    五分钟搞定WebRTC视频录制
    一分钟教你构建属于你的视频会议SDK
    史上最全的WebRTC服务器技术选型分析
    数据库设计之思考
  • 原文地址:https://www.cnblogs.com/joannacode/p/6130335.html
Copyright © 2020-2023  润新知