208. Implement Trie (Prefix Tree)

Link

Solution

主要是要想到那個Node的資料結構。其餘就會很直覺了。

class Node{
    public char val;
    public boolean isWord;
    public Node[] nextOne = new Node[26];
    
    public Node(char c){
        this.val = c;
    }
    
}


class Trie {

    /** Initialize your data structure here. */
    private Node root;
    
    public Trie() {
       root = new Node(' ');
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        Node it = root;
        for(char c : word.toCharArray()){
            if(it.nextOne[c-'a'] == null){
                it.nextOne[c-'a'] = new Node(c);
            }
            it = it.nextOne[c-'a'];
        }
        it.isWord = true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        Node it = root;
        for(char c : word.toCharArray()){
            if(it.nextOne[c-'a'] == null){
                return false;
            }
            it = it.nextOne[c-'a'];
        }
        return it.isWord;
        
        
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        Node it = root;
        for(char c : prefix.toCharArray()){
            if(it.nextOne[c-'a'] == null){
                return false;
            }
            it = it.nextOne[c-'a'];        
        }
        return true;
    }
}

Last updated

Was this helpful?