lc 208. 实现 Trie (前缀树)

    科技2025-10-01  20

    class Trie { private class Node{ private Node[] next; // true代表一个单词结尾于此 private boolean hasWord; public Node(){ next=new Node[26]; } } private Node root; /** Initialize your data structure here. */ public Trie() { root=new Node(); } private Node insert(String w,Node n,int d){ // 为空,找到插入点 if(n==null){ n=new Node(); } // 是否单词已经到了最后一个字母 if(d==w.length()){ n.hasWord=true; return n; } // 如果还剩下字母,那么继续插入 int c=w.charAt(d)-'a'; n.next[c]=insert(w,n.next[c],d+1); return n; } /** Inserts a word into the trie. */ public void insert(String word) { root=insert(word,root,0); } private boolean search(String w,Node n,int d){ if(n==null){ return false; } if(d==w.length()){ return n.hasWord; } int c=w.charAt(d)-'a'; return search(w,n.next[c],d+1); } /** Returns if the word is in the trie. */ public boolean search(String word) { return search(word,root,0); } private boolean startsWith(String w,Node n,int d){ if(n==null){ return false; } if(d==w.length()){ return true; } int c=w.charAt(d)-'a'; return startsWith(w,n.next[c],d+1); } /** Returns if there is any word in the trie that starts with the given prefix. */ public boolean startsWith(String prefix) { return startsWith(prefix,root,0); } } /** * 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); */

     

    Processed: 0.012, SQL: 8