zoukankan      html  css  js  c++  java
  • 前缀树(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;
        }
    }
    
  • 相关阅读:
    NumPy 位运算
    NumPy 数组迭代
    NumPy 广播
    NumPy 基于数值区间创建数组
    NumPy 数组切片
    NumPy 基于已有数据创建数组
    NumPy 数组创建
    NumPy 数据类型
    NumPy ndarray
    区块链技术学习指引
  • 原文地址:https://www.cnblogs.com/hunter-w/p/14398202.html
Copyright © 2011-2022 走看看