Leetcode 208. Implement Trie (Prefix Tree)

来源:互联网 发布:osi模型网络层相关 编辑:程序博客网 时间:2024/06/05 15:00

Implement a trie with insertsearch, and startsWith methods.

Note:

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


public class Trie {        private TrieNode root;        public class TrieNode{        TrieNode[] arr;        boolean isEnd;        public TrieNode() {            this.arr = new TrieNode[26];        }    }        public Trie() {        root = new TrieNode();    }        public void insert(String word) {        TrieNode p = root;        for (int i = 0; i < word.length(); i++) {            int index = word.charAt(i) - 'a';            if (p.arr[index] == null) {                TrieNode temp = new TrieNode();                p.arr[index] = temp;                p = temp;            }            else {                p = p.arr[index];            }        }        p.isEnd = true;    }        public boolean search(String word) {        TrieNode p = root;        for (int i = 0; i < word.length(); i++) {            int index = word.charAt(i) - 'a';            if (p.arr[index] == null) return false;            p = p.arr[index];        }        return p != null && p.isEnd;    }        public boolean startsWith(String prefix) {        TrieNode p = root;        for (int i = 0; i < prefix.length(); i++) {            int index = prefix.charAt(i) - 'a';            if (p.arr[index] == null) return false;            p = p.arr[index];        }        return true;    }}


0 0
原创粉丝点击