leetcode 208. 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.

这道题考察的就是字典树的构造,本题是使用HashMap来完成构造,说实话之前没有学过字典树俄构造,这也算第一次吧,不过这个数据结构真的很棒。

本题给我的最大的启发就是注意使用HashMap等数据结构。

代码如下:

import java.util.HashMap;
import java.util.Map;
/*
 * 字典树,这个需要好好学习
 * http://blog.csdn.net/xudli/article/details/45598337
 * 记着吧
 * */
class TrieNode
{
    char c;
    boolean isLeaf=false;
    Map<Character, TrieNode> childred=new HashMap<Character, TrieNode>();

    public TrieNode(char d) 
    {
        c=d;
    }

    public TrieNode() 
    {
    }
}

public class Trie
{
    TrieNode root=null;
    /** Initialize your data structure here. */
    public Trie() 
    {
        root=new TrieNode();
    }

    /** Inserts a word into the trie. */
    public void insert(String word)
    {
        Map<Character, TrieNode> childred=root.childred;
        for(int i=0;i<word.length();i++)
        {
            char c=word.charAt(i);
            TrieNode one=null;
            if(childred.containsKey(c))
                one=childred.get(c);
            else
            {
                one=new TrieNode(c);
                childred.put(c, one);
            }
            childred=one.childred;
            if(i==word.length()-1)
                one.isLeaf=true;
        }
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) 
    {
        TrieNode res=searchNode(word);
        if(res!=null && res.isLeaf)
            return true;
        else 
            return false;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) 
    {
        TrieNode res=searchNode(prefix);
        if(res!=null)
            return true;
        else 
            return false;
    }


    private TrieNode searchNode(String word) 
    {
        TrieNode res=null;
        Map<Character, TrieNode> childred=root.childred;
        for(int i=0;i<word.length();i++)
        {
            char c=word.charAt(i);
            if(childred.containsKey(c)==false)
                return null;
            else
            {
                res=childred.get(c);
                childred=res.childred;
            }
        }
        return res;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值