zoukankan      html  css  js  c++  java
  • 数据结构—— Trie (前缀树)

    实现一个 Trie (前缀树),包含 插入, 查询, 和 查询前缀这三个操作。
    Trie trie = new Trie();
    trie.insert(“apple”);
    trie.search(“apple”); // 返回 true
    trie.search(“app”); // 返回 false
    trie.startsWith(“app”); // 返回 true
    trie.insert(“app”);
    trie.search(“app”); // 返回 true

    思路:构造一个多叉树数据结构,每个父节点最多有26个子节点,分别表示26个字母,同时每个节点还存在一个结尾标志位,表示该节点是否位一个单词的末尾节点。树的操作是重点,首先在全局变量中,我们得到树的根节点,每次操作都从根节点出发。
    插入操作就是遍历树,如果不存在相应的节点则实例化新节点,直到遍历到尾节点,并将尾节点的标志置为。
    查询和查询前缀的方法类似,对树进行遍历,不存在节点直接返回false,最后返回判断尾节点的标志位。

    class Node {
        public Node[] val;
        public boolean isEnd = false;
    
        public Node() {
            val = new Node[26];
        }
    }
    
    class Trie {
        Node root;
        /** Initialize your data structure here. */
        public Trie() {
            root = new Node();
        }
        
        /** Inserts a word into the trie. */
        public void insert(String word) {
            Node cur = root;
            for(int i = 0; i < word.length(); i ++) {
                if(cur.val[word.charAt(i) - 'a'] == null) {
                    cur.val[word.charAt(i) - 'a'] = new Node();
                }
    
                cur = cur.val[word.charAt(i) - 'a'];
            }
    
            cur.isEnd = true;
        }
        
        /** Returns if the word is in the trie. */
        public boolean search(String word) {
            Node cur = root;
            for(int i = 0; i < word.length(); i++) {
                if(cur.val[word.charAt(i) - 'a'] == null) return false;
                cur = cur.val[word.charAt(i) - 'a'];
            }
    
            return cur.isEnd;
        }
        
        /** Returns if there is any word in the trie that starts with the given prefix. */
        public boolean startsWith(String prefix) {
            Node cur = root;
            for(int i = 0; i < prefix.length(); i++) {
                if(cur.val[prefix.charAt(i) - 'a'] == null) return false;
                cur = cur.val[prefix.charAt(i) - 'a'];
            }
    
            return true;
        }
    }
    
  • 相关阅读:
    数据库压力测试的参考地址
    Infopath表单部署到Farm的方法
    oracle 的几个开发工具比较
    智能Web算法/NLP 参考图书
    Wireshark & Ethereal包分析工具【图书节选】
    Sharepoint内置的”翻译管理库”体验
    开发相关“视频公开课webcast”资源地址
    读书:架构师的12项技能 12 ESSENTIAL SKILLS FOR SOFTWARE ARCHITECTS
    Linux 下Oracle Client JAVA JDBC 集成点滴
    MOS2010的界面介绍和定制方法简介【资料汇集】
  • 原文地址:https://www.cnblogs.com/lippon/p/14117713.html
Copyright © 2011-2022 走看看