• 前缀树(Trie)


    实现前缀树

    知识点

    Trie (发音为 "try") 或前缀树是一种树数据结构,用于检索字符串数据集中的键。
    常见的应用场景有:

    • 自动补全
    • 拼写检查
    • IP路由(最长前缀匹配)
    • 打字预测

    示例

    1. 实现 Trie (前缀树)
    class TrieNode {
        private final int R = 26;
        private TrieNode[] links;
        private boolean isEnd = false;
    
        public TrieNode() {
            links = new TrieNode[R];
        }
    
        public boolean containsKey(char ch) {
            return links[ch-'a'] != null;
        }
    
        public TrieNode get(char ch) {
            return links[ch-'a'];
        }
    
        public void put(char ch, TrieNode node) {
            links[ch-'a']=node;
        }
    
        public boolean isEnd() {
            return isEnd;
        }
    
        public void setEnd() {
            isEnd = true;
        }
    }
    
    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;
            char[] charArray = word.toCharArray();
            int len = charArray.length;
            for (int i=0;i<len;i++) {
                if (!node.containsKey(charArray[i])) {
                    node.put(charArray[i], new TrieNode());
                }
                node=node.get(charArray[i]);
            }
    
            node.setEnd();
        }
        
        /** Returns if the word is in the trie. */
        public boolean search(String word) {
            TrieNode node = root;
            char[] charArray = word.toCharArray();
            int len = charArray.length;
            for (int i=0;i<len;i++) {
                if (!node.containsKey(charArray[i])) {
                    return false;
                }
                node=node.get(charArray[i]);
            }
    
            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;
            char[] charArray = prefix.toCharArray();
            int len = charArray.length;
            for (int i=0;i<len;i++) {
                if (!node.containsKey(charArray[i])) {
                    return false;
                }
                node=node.get(charArray[i]);
            }
    
            return true;
        }
    }
    
  • 相关阅读:
    datasnap 2010 为DataSnap系统服务程序添加描述
    uLanguage.pas
    cxgrid上如何取FOOTER上合计的值
    cxgrid经典用法
    datasnap 2010 DataSnap服务端和客户端发布分发方法
    php_network_getaddresses: getaddrinfo failed 原因
    查看crontab运行状态
    laravel 开启定时任务需要操作
    解决cron不执行的问题
    UPdate语句
  • 原文地址:https://www.cnblogs.com/hunter-w/p/14398202.html
Copyright © 2020-2023  润新知