`

Implement Trie (Prefix Tree)

阅读更多
Implement a trie with insert, search, and startsWith methods.

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

题目的要求很简单,完成一个前缀树的插入,搜索等功能。

Trie为前缀树,又称字典树或单词查找树,是一种用于快速检索的多叉树结构,例如,基于英文字母的前缀树是一个26叉树(a-z),基于数字的前缀树是一个10叉树(0-9)。前缀树的核心思想是用空间换时间。利用字符串的公共前缀来降低查询时间的开销,从而可以提高效率。前缀树的缺点是如果系统中存在大量字符串,并且这些字符串基本没有公共前缀,此时需要占用大量的内存。有关前缀树的基本性质大家可以网上查询,这里不再赘述。

对于这道题目有一个search方法用来查询字典中是否存在这个单词,startsWith方法用来检查是否存在一个前缀。因此实现search方法时我们要借助一个变量isLast来判段,字典中这个是否为一个完整的单词。代码如下:
class TrieNode {
    TrieNode[] trieNode;
    boolean isLast;
    // Initialize your data structure here.
    public TrieNode() {
        trieNode = new TrieNode[26];
        isLast = false;
    }
}

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(char c : word.toCharArray()) {
            if(cur.trieNode[c - 'a'] == null)
                cur.trieNode[c - 'a'] = new TrieNode();
            cur = cur.trieNode[c - 'a'];
        }
        cur.isLast = true;
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        TrieNode cur = root;
        if(root == null) return false;
        for(char c : word.toCharArray()) {
            if(cur.trieNode[c - 'a'] == null) return false;
            cur = cur.trieNode[c - 'a'];
        }
        if(cur.isLast == true) return true;
        return false;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        TrieNode cur = root;
        if(root == null) return false;
        for(char c : prefix.toCharArray()) {
            if(cur.trieNode[c - 'a'] == null) return false;
            cur = cur.trieNode[c - 'a'];
        }
        return true;
    }
}

// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");

1
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics