码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Implement Trie (Prefix Tree)

时间:2015-12-06 13:06:50      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

class TrieNode {
    // Initialize your data structure here.
    TrieNode[] child;
    boolean isWord;
    public TrieNode() {
        child = new TrieNode[26];
        isWord = false;
    }
}

public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        insert(word, root);
    }
    public void insert(String word, TrieNode root) {
        if (word.length() == 0) {
            root.isWord = true;
            return;
        }
        char ch = word.charAt(0);
        if (root.child[ch - ‘a‘] == null) {
            root.child[ch - ‘a‘] = new TrieNode();
        }
        insert(word.substring(1), root.child[ch - ‘a‘]);
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        return search(word, root);
    }
    public boolean search(String word, TrieNode root) {
        if (word.length() == 0) {
            return root.isWord;
        }
        char ch = word.charAt(0);
        if (root.child[ch - ‘a‘] == null) {
            return false;
        } else {
           return search(word.substring(1), root.child[ch - ‘a‘]);
        }
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
       return startsWith(prefix, root);
    }
    public boolean startsWith(String prefix, TrieNode root) {
        if (prefix.length() == 0) {
            return true;
        }
        char ch = prefix.charAt(0);
        if (root.child[ch - ‘a‘] == null) {
            return false;
        } else {
            return startsWith(prefix.substring(1), root.child[ch - ‘a‘]);
        }
    }
}

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

 

[LeetCode]Implement Trie (Prefix Tree)

标签:

原文地址:http://www.cnblogs.com/vision-love-programming/p/5023347.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!