Leetcode 208 Implement Trie (Prefix Tree)

来源:互联网 发布:软件项目简介模板 编辑:程序博客网 时间:2024/05/19 14:52

Implement a trie with insertsearch, and startsWith methods.

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

trie 就是prefix tree 用word的前缀进行索引的tree

基本思路是每一个node都有一个list(结构为treenode),对应26个字母,也就是指向下一层的node

public class Trie {    TreeNode root;        /** Initialize your data structure here. */    public Trie() {        root = new TreeNode();    }        /** Inserts a word into the trie. */    public void insert(String word) {        if(search(word) || word == null){            return;        }        TreeNode node = root;        for(int i = 0; i< word.length(); i++){            char now = word.charAt(i);            if(node.list[now - 'a'] == null){               node.list[now - 'a'] = new TreeNode();               node = node.list[now - 'a'];               continue;            } else {            node = node.list[now - 'a'];               continue;            }        }       node.isEnd = true;     }        /** Returns if the word is in the trie. */    public boolean search(String word) {        TreeNode node = root;        for(int i = 0; i< word.length(); i++){            char now = word.charAt(i);            if(node.list[now - 'a'] == null){               return false;            } else {            node = node.list[now - 'a'];               continue;            }        }        return node.isEnd == true;    }        /** Returns if there is any word in the trie that starts with the given prefix. */    public boolean startsWith(String prefix) {        TreeNode node = root;        for(int i = 0; i< prefix.length(); i++){            char now = prefix.charAt(i);            if(node.list[now - 'a'] == null){             return false;            } else {            node = node.list[now - 'a'];               continue;            }        }        return true;    }            private class TreeNode{        boolean isEnd = false;//加了个flag是为了区分当前是不是一个word的最末char        TreeNode[] list = new TreeNode[26];        public TreeNode(){                    }    }}/** * 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); */




原创粉丝点击