Implement Trie (Prefix Tree) LeetCode Java

来源:互联网 发布:nginx 日志配置 编辑:程序博客网 时间:2024/04/28 05:55

Implement a trie with insert, search, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

这道题目主要是考察Trie Tree。
明白了什么是Trie Tree,这道题就不难了。

Trie Tree是一个典型的用空间换时间的例子。
不明白的同学可以自行百度。

这里也转了一段对Trie Tree的解释

以下这段内容转自:http://blog.csdn.net/beiyetengqing/article/details/7856113

关注Trie 这种结构已经很久,Trie有一个很有趣的用途,那就是自动提示。而且,前不久在一次面试里,也需要用Trie来解答。所以,在此对这个数据结构进行总结。
Trie,又称单词查找树或键树,是一种树形结构。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大限度地减少无谓的字符串比较,查询效率比哈希表高。
它有3个基本性质:

根节点不包含字符,除根节点外每一个节点都只包含一个字符。
从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
每个节点的所有子节点包含的字符都不相同。

下面这个图就是Trie的表示,每一条边表示一个字符,如果结束,就用星号表示。在这个Trie结构里,我们有下面字符串,比如do, dork, dorm等,但是Trie里没有ba, 也没有sen,因为在a, 和n结尾,没有结束符号(星号)。

这里写图片描述

有了这样一种数据结构,我们可以用它来保存一个字典,要查询改字典里是否有相应的词,是否非常的方便呢?我们也可以做智能提示,我们把用户已经搜索的词存在Trie里,每当用户输入一个词的时候,我们可以自动提示,比如当用户输入 ba, 我们会自动提示 bat 和 baii.
现在来讨论Trie的实现。

这道题目应该有很多不同的解法,我AP的程序如下:

class TrieNode {    // Initialize your data structure here.    public TrieNode[] children=new TrieNode[26];;    public char c;    public boolean value;    public TrieNode() {    }    public TrieNode(char c){        this.c=c;    }}public class Trie {    private TrieNode root;    public Trie() {        root = new TrieNode();    }    // Inserts a word into the trie.    public void insert(String word) {        TrieNode cur=root;        for(int i=0;i<word.length();i++){            int index=word.charAt(i)-'a';            if(cur.children[index]==null){                cur.children[index]=new TrieNode(word.charAt(i));            }            cur=cur.children[index];        }        cur.value=true;    }    // Returns if the word is in the trie.    public boolean search(String word) {        TrieNode cur=root;        for(int i=0;i<word.length();i++){            int index=word.charAt(i)-'a';            if(cur.children[index]==null){                return false;            }            cur=cur.children[index];        }        if(!cur.value)            return false;        return true;    }    // Returns if there is any word in the trie    // that starts with the given prefix.    public boolean startsWith(String prefix) {        TrieNode cur=root;        for(int i=0;i<prefix.length();i++){            int index=prefix.charAt(i)-'a';            if(cur.children[index]==null){                return false;            }            cur=cur.children[index];        }        return true;      }}// Your Trie object will be instantiated and called as such:// Trie trie = new Trie();// trie.insert("somestring");// trie.search("key");
0 0
原创粉丝点击