[leedcode 208] Implement Trie (Prefix Tree)

Trie树又被称为字典树、前缀树,是一种用于快速检索的多叉树。Tried树可以利用字符串的公共前缀来节省存储空间。

但如果系统存在大量没有公共前缀的字符串,相应的Trie树将非常消耗内存。(下图为Wiki上的Trie树示意图, https://en.wikipedia.org/wiki/Trie)

  1. 子节点用hashMap表示
  2. isWord标记从根节点到该节点是否表示一个单词,还是另一单词的前缀。

 

Implement a trie with insertsearch, and startsWith methods.

class TrieNode {
    // Initialize your data structure here.
        boolean isWord;
        public HashMap<Character,TrieNode> nexts;
        public TrieNode(){
            nexts=new HashMap<Character,TrieNode>();
        }
    
}

public class Trie {
    private TrieNode root;

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

    // Inserts a word into the trie.
    public void insert(String word) {
        int start=0;
        int end=word.length();
        TrieNode p=root;
        while(start<end){
           TrieNode node= p.nexts.get(word.charAt(start));
           if(node!=null){
               p=node;
               start++;
           }else break;
        }
        while(start<end){
            TrieNode trie=new TrieNode();
            p.nexts.put(word.charAt(start),trie);
            p=trie;
            start++;
        }
        p.isWord=true;
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        TrieNode p=root;
        for(int i=0;i<word.length();i++){
           TrieNode child= p.nexts.get(word.charAt(i));
           if(child==null){
               return false;
           }
           p=child;
        }
        return p.isWord;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        TrieNode p=root;
        for(int i=0;i<prefix.length();i++){
            TrieNode child=p.nexts.get(prefix.charAt(i));
            if(child==null) return false;
            p=child;
        }
        return true;
    }
}

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

 

posted @ 2015-08-04 22:27  ~每天进步一点点~  阅读(137)  评论(0编辑  收藏  举报