ð 208. å®ç° Trie (åçŒæ )
2022幎10æ10æ¥
- algorithm
 
ð 208. å®ç° Trie (åçŒæ )
éŸåºŠ: ð
é®é¢æè¿°

è§£æ³
class Trie {
    // æè·¯ïŒ
    // äžå
± 26 䞪å°ååæ¯ïŒæä»¥æé  26 åæ 
    Node root;
    public Trie() {
        this.root = new Node('a'); // åå§åæ ¹èç¹ïŒæ¥æŸå
玠æ¶ïŒä»æ ¹èç¹çå©ååŒå§ïŒäœäžºéŠåæ¯
    }
    
    public void insert(String word) {
        int len = word.length();
        Node cur = root;
        for(int i = 0; i < len; i ++) {
            char c = word.charAt(i);
            int index = c - 'a';
            if(cur.child[index] == null) {
                cur.child[index] = new Node(c);
            }
            cur = cur.child[index];
        }
        cur.end = true; // æ è®°æ¯æäžªåè¯çæåäžäžªå笊æåšçèç¹
    }
    
    public boolean search(String word) {
        // æ¥æŸ å®å
šå¹é
åè¯ - éèŠå°èŸŸå¶åèç¹
        Node cur = root;
        int len = word.length();
        for(int i = 0; i < len; i ++) {
            char c = word.charAt(i);
            int index = c - 'a';
            if(cur.child[index] == null) {
                return false;
            } 
            cur = cur.child[index];
        }
        // éèŠä¿è¯ cur 没æä»»äœåèç¹
        return cur.end;
    }
    
    public boolean startsWith(String prefix) {
        // æ¥æŸ åçŒåè¯ - äžéèŠå°èŸŸå¶åèç¹
        Node cur = root;
        int len = prefix.length();
        for(int i = 0; i < len; i ++) {
            char c = prefix.charAt(i);
            int index = c - 'a';
            if(cur.child[index] == null) {
                return false;
            } 
            cur = cur.child[index];
        }
        return true;
    }
}
// æé  26 åæ  èç¹ç±»
class Node {
    char val;
    boolean end;
    Node[] child;
    public Node(char val) {
        this.val = val;
        this.end = false; // æ è®°è¯¥èç¹æ¯åŠäžºåè¯çæåäžäžªèç¹
        this.child = new Node[26];
    }
}
/**
 * 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);
 */
èŸåº
