Prefix tree

The trie, or prefix tree, is a data structure for storing strings or other sequences in a way that allows for a fast look-up. In its simplest form it can be used as a list of keywords or a dictionary.
By associating each string with an object it can be used as an alternative to a hashmap. The name 'trie' comes from the word 'retrieval'.

The basic idea behind a trie is that each successive letter is stored as a separate node. To find out if the word 'cat' is in the list you start at the root and look up the 'c' node. Having found
the 'c' node you search the list of c's children for an 'a' node, and so on. To differentiate between 'cat' and 'catalog' each word is ended by a special delimiter.

The figure below shows a schematic representation of a partial trie:

Implementation

The fastest way to implement this is with fixed size arrays. Unfortunately this only works if you know which characters can show up in the sequences. For keywords with 26 letters its a fast but space
consuming option, for unicode strings its pretty much impossible.

Instead of fixed sizes arrays you can use a linked list at each node. This has obvious space advantages, since no more empty spaces are stored. Unfortunately searching a long linked list is rather
slow. For example to find the word 'zzz' you might need 3 times 26 steps.

Faster trie algorithms have been devised that lie somewhere between these two extremes in terms of speed and space consumption. These can be found by searching google.

Fun & games with prefix trees

Prefix trees are a bit of an overlooked data structure with lots of interesting possibilities.

Storage

By storing values at each leaf node you can use them as a kind of alternative hashmap, although when working with unicode strings a hashmap will greatly outperform a trie.

As a dictionary

Looking up if a word is in a trie takes O(n) operations, where n is the length of the word. Thus - for array implementations - the lookup speed doesn't change with increasing trie size.

Word completion

Word completion is straightforward to implement using a trie: simply find the node corresponding to the first few letters, and then collape the subtree into a list of possible endings.

This can be used in autocompleting user input in text editors or the T9 dictionary on your phone

Censoring strings

Given a large list of swear words and a string to censor a trie offers a speed advantage over a simple array of strings. If the swear word can appear anywhere in the string you'll need to attempt
to match it from any possible starting offset. With a string of m characters and a list of n words this would mean m*n string comparisons.

Using a trie you can attempt to find a match from each given offset in the string, this means m trie lookups. Since the speed of a trie lookup scales well with an increasing number of words this is
considerably faster than the array lookup.

Java linked list implementation

Just for fun, here's a java linked list implementation. Keep in mind that this is a fairly slow implementation. For serious speed boosts you'll need to investigate double or triple-array tries.

Please note: the version below is a simplified version intended only to give some insight into the workings of the Trie. For the full version please see theDownloads
section
.

publicclass Trie

{

    /**

     * The delimiter used in this word to tell where words end. Without a proper delimiter either A.

     * a lookup for 'win' would return false if the list also contained 'windows', or B. a lookup

     * for 'mag' would return true if the only word in the list was 'magnolia'

     *

     * The delimiter should never occur in a word added to the trie.

     */

    public
final static
char DELIMITER = '\u0001';



    /**

     * Creates a new Trie.

     */

    public Trie()

    {

        root =
new Node('r');

        size = 0;

    }



    /**

     * Adds a word to the list.

     * @param word The word to add.

     * @return True if the word wasn't in the list yet

     */

    public
boolean add(String word)

    {

        if (add(root, word+ DELIMITER,
0))

        {

            size++;

            int n
= word.length();

            if
(n > maxDepth) maxDepth
= n;

            return
true;

        }

        return
false;

    }



    /*

     * Does the real work of adding a word to the trie

     */

    private
boolean add(Node root, String word,int offset)

    {

        if (offset== word.length())return
false;

        int c
= word.charAt(offset);



        // Search for node to add to

        Node last =
null, next = root.firstChild;

        while
(next !=
null)

        {

            if
(next.value < c)

            {

                // Not found yet, continue searching

                last = next;

                next = next.nextSibling;

            }

            else
if (next.value
== c)

            {

                // Match found, add remaining word to this node

                return add(next, word, offset+
1);

            }

            // Because of the ordering of the list getting here means we won't

            // find a match

            else
break;

        }



        // No match found, create a new node and insert

        Node node =
new Node(c);

        if (last==
null)

        {

            // Insert node at the beginning of the list (Works for next == null

            // too)

            root.firstChild = node;

            node.nextSibling = next;

        }

        else

        {

            // Insert between last and next

            last.nextSibling = node;

            node.nextSibling = next;

        }



        // Add remaining letters

        for (int i= offset
+ 1; i< word.length(); i++)

        {

            node.firstChild =new Node(word.charAt(i));

            node = node.firstChild;

        }

        return
true;

    }



    /**

     * Searches for a word in the list.

     *

     * @param word The word to search for.

     * @return True if the word was found.

     */

    public
boolean isEntry(String word)

    {

        if (word.length()==
0)

            throw
new IllegalArgumentException("Word can't be empty");

        return isEntry(root, w+ DELIMITER,
0);

    }



    /*

     * Does the real work of determining if a word is in the list

     */

    private
boolean isEntry(Node root,
String word, int offset)

    {

        if (offset== word.length())return
true;

        int c
= word.charAt(offset);



        // Search for node to add to

        Node next = root.firstChild;

        while
(next !=
null)

        {

            if
(next.value < c) next= next.nextSibling;

            else
if (next.value
== c)
return isEntry(next, word, offset +1);

            else
return false;

        }

        return
false;

    }



    /**

     * Returns the size of this list;

     */

    public
int size()

    {

        return size;

    }



    /**

     * Returns all words in this list starting with the given prefix

     *

     * @param prefix The prefix to search for.

     * @return All words in this list starting with the given prefix, or if no such words are found,

     *         an array containing only the suggested prefix.

     */

    public
String[] suggest(String prefix)

    {

        return suggest(root, prefix,0);

    }



    /*

     * Recursive function for finding all words starting with the given prefix

     */

    private
String[] suggest(Node root,String word,
int offset)

    {

        if (offset== word.length())

        {

            ArrayList<String> words
= new ArrayList<String>(size);

            char[] chars=
new
char[maxDepth];

            for
(int i
= 0; i < offset; i++)

                chars[i]
= word.charAt(i);

            getAll(root, words, chars, offset);

            return words.toArray(newString[words.size()]);

        }

        int c
= word.charAt(offset);



        // Search for node to add to

        Node next = root.firstChild;

        while
(next !=
null)

        {

            if
(next.value < c) next= next.nextSibling;

            else
if (next.value
== c)
return suggest(next, word, offset +1);

            else
break;

        }

        return
new String[]{ word
};

    }



    /**

     * Searches a string for words present in the trie and replaces them with stars (asterixes).

     * @param z The string to censor

     */

    public
String censor(String s)

    {

        if (size==
0)
return s;

        String z = s.toLowerCase();

        int n
= z.length();

        StringBuilder buffer =
new StringBuilder(n);

        int match;

        char star
= '*';

        for (int i=
0; i < n;)

        {

            match = longestMatch(root, z, i,0,
0);

            if
(match > 0)

            {

                for
(int j
= 0; j < match; j++)

                {

                    buffer.append(star);

                    i++;

                }

            }

            else

            {

                buffer.append(s.charAt(i++));

            }

        }

        return buffer.toString();

    }



    /*

     * Finds the longest matching word in the trie that starts at the given offset...

     */

    private
int longestMatch(Node root,
String word, int offset,int depth,
int maxFound)

    {

        // Uses delimiter = first in the list!

        Node next = root.firstChild;

        if (next.value== DELIMITER) maxFound
= depth;

        if (offset== word.length())return
maxFound;

        int c
= word.charAt(offset);



        while
(next !=
null)

        {

            if
(next.value < c) next= next.nextSibling;

            else
if (next.value
== c)
return longestMatch(next, word,

                offset + 1, depth
+ 1, maxFound);

            else
return maxFound;

        }

        return maxFound;

    }



    /*

     * Represents a node in the trie. Because a node's children are stored in a linked list this

     * data structure takes the odd structure of node with a firstChild and a nextSibling.

     */

    private
class Node

    {

        public
int value;

        public Node firstChild;

        public Node nextSibling;



        public Node(int value)

        {

            this.value= value;

            firstChild =
null;

            nextSibling =
null;

        }

    }





    private Node root;

    private
int size;

    private
int maxDepth; // Not exact, but bounding for the maximum

}

Please note: the code given above is intended only to give some insight into the workings of the Trie. For the full version of the class please see theDownloads
section
.

Prefix tree的更多相关文章

  1. Leetcode: Implement Trie (Prefix Tree) && Summary: Trie

    Implement a trie with insert, search, and startsWith methods. Note: You may assume that all inputs a ...

  2. leetcode面试准备:Implement Trie (Prefix Tree)

    leetcode面试准备:Implement Trie (Prefix Tree) 1 题目 Implement a trie withinsert, search, and startsWith m ...

  3. 【LeetCode】208. Implement Trie (Prefix Tree)

    Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Note:You ...

  4. [LeetCode] 208. Implement Trie (Prefix Tree) ☆☆☆

    Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs ar ...

  5. 笔试算法题(39):Trie树(Trie Tree or Prefix Tree)

    议题:TRIE树 (Trie Tree or Prefix Tree): 分析: 又称字典树或者前缀树,一种用于快速检索的多叉树结构:英文字母的Trie树为26叉树,数字的Trie树为10叉树:All ...

  6. Trie树(Prefix Tree)介绍

    本文用尽量简洁的语言介绍一种树形数据结构 -- Trie树. 一.什么是Trie树 Trie树,又叫字典树.前缀树(Prefix Tree).单词查找树 或 键树,是一种多叉树结构.如下图: 上图是一 ...

  7. 字典树(查找树) leetcode 208. Implement Trie (Prefix Tree) 、211. Add and Search Word - Data structure design

    字典树(查找树) 26个分支作用:检测字符串是否在这个字典里面插入.查找 字典树与哈希表的对比:时间复杂度:以字符来看:O(N).O(N) 以字符串来看:O(1).O(1)空间复杂度:字典树远远小于哈 ...

  8. LeetCode208 Implement Trie (Prefix Tree). LeetCode211 Add and Search Word - Data structure design

    字典树(Trie树相关) 208. Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith  ...

  9. 【leetcode】208. Implement Trie (Prefix Tree 字典树)

    A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently s ...

随机推荐

  1. Linux--NFS和DHCP服务器

     (1) 在网络中,时常需要进行文件的共享,如果都是在Linux系统下,可以使用NFS 来搭建文件服务器,达到文件共享的目的. (2) 在网络管理中,为了防止IP 冲突和盗用,有效的控制IP 资源 ...

  2. EBS各个应用简称

     模块全称 Banking Center 模块简称 FPT 服务器目录 FPT_TOP Billing Connect CUE CUE_TOP CADView-3D DDD DDD_TOP CPG ...

  3. iOS应用程序工程文件以及启动流程

    转载请标明出处: http://blog.csdn.net/xmxkf/article/details/51351188 本文出自:[openXu的博客] iOS程序启动流程 完整启动流程 UIApp ...

  4. 【Netty源码分析】客户端connect服务端过程

    上一篇博客[Netty源码分析]Netty服务端bind端口过程 我们介绍了服务端绑定端口的过程,这一篇博客我们介绍一下客户端连接服务端的过程. ChannelFuture future = boos ...

  5. UE4读取scv文件 -- 数据驱动游戏性元素

    官方文档链接:http://docs.unrealengine.com/latest/CHN/Gameplay/DataDriven/index.html 略懒,稍微麻烦重复的工作,总希望能找人帮忙一 ...

  6. JDK8帮助文档生成-笔记

    JDK8 出来了,以前习惯了使用.CHM文件来查看API,现在想也这样,这里自己制作了一下,记录一下. 1.需要的工具: ①JD2CHM;②API文档③HTMLlHelper 遇到的问题主要是不知道去 ...

  7. 【Shader拓展】Illustrative Rendering in Team Fortress 2

    写在前面 早在使用ramp texture控制diffuse光照一文就提到了这篇著名的论文.Valve公司发表的其他成果可见这里.这是Valve在2007年发表的一篇非常具有影响力的文章,我的导师也提 ...

  8. 【Unity Shaders】游戏性和画面特效——创建一个夜视效果的画面特效

    本系列主要参考<Unity Shaders and Effects Cookbook>一书(感谢原书作者),同时会加上一点个人理解或拓展. 这里是本书所有的插图.这里是本书所需的代码和资源 ...

  9. 安卓ListView的性能优化

    在安卓APP中LIstView这个控件可以说基本上是个APP就会用到,但是关于ListView除了需要了解其最基本的用法外,作为一个要做出高性能APP的程序员还需了解一些关于LIstView控件性能优 ...

  10. Android进阶(二十七)Android原生扰人烦的布局

    Android原生扰人烦的布局 在开发Android应用时,UI布局是一件令人烦恼的事情.下面主要讲解一下Android中的界面布局. 一.线性布局(LinearLayout) 线性布局分为: (1) ...