LeetCode 208 Implement Trie (Prefix Tree)

来源:互联网 发布:孙子涵是网络歌手吗 编辑:程序博客网 时间:2024/05/18 01:22
mplement a trie with insert, search, andstartsWith methods.

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


题目链接:https://leetcode.com/problems/implement-trie-prefix-tree/

题目分析:实现一个字典树,每个节点有26个孩子[a - z]

class TrieNode {    // Initialize your data structure here.    final int SIZE = 26;    boolean isWord;    boolean isPrefix;    TrieNode[] next;    public TrieNode() {        isWord = false;        isPrefix = false;        next = new TrieNode[SIZE];        for(int i = 0; i < SIZE; i ++) {            next[i] = null;        }    }}public class Trie {    private TrieNode root;    public Trie() {        root = new TrieNode();    }    // Inserts a word into the trie.    public void insert(String word) {        int len = word.length();        TrieNode p = new TrieNode();        p = root;        for(int i = 0; i < len; i++) {            int idx = word.charAt(i) - 'a';            if(p.next[idx] == null) {                p.next[idx] = new TrieNode();            }            p = p.next[idx];            p.isPrefix = true;        }        p.isWord = true;        return;    }    // Returns if the word is in the trie.    public boolean search(String word) {        int len = word.length();        TrieNode p = new TrieNode();        p = root;        for(int i = 0; i < len; i++) {            int idx = word.charAt(i) - 'a';            if(p.next[idx] == null && i < len) {                return false;            }            p = p.next[idx];        }        return p.isWord;    }    // Returns if there is any word in the trie    // that starts with the given prefix.    public boolean startsWith(String prefix) {        int len = prefix.length();        TrieNode p = new TrieNode();        p = root;        for(int i = 0; i < len; i++) {            int idx = prefix.charAt(i) - 'a';            if(p.next[idx] == null && i < len) {                return false;            }            p = p.next[idx];        }        return p.isPrefix;    }}// Your Trie object will be instantiated and called as such:// Trie trie = new Trie();// trie.insert("somestring");// trie.search("key");



0 0
原创粉丝点击