Skip to content

Latest commit

 

History

History
71 lines (57 loc) · 1.59 KB

1.6 - Trie.md

File metadata and controls

71 lines (57 loc) · 1.59 KB

Trie

class TrieNode {
    public TrieNode[] children = new TrieNode[26];
    public boolean isEnd;

    public TrieNode() {}
}

public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        TrieNode node = root;

        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (node.children[c - 'a'] == null) {
                node.children[c - 'a'] = new TrieNode();
            }
            node = node.children[c - 'a'];
        }

        node.isEnd = true;
    }

    // Returns true if the word is in the trie.
    public boolean search(String word) {
        TrieNode node = searchNode(word);

        if (node == null) {
            return false;
        } else {
            return node.isEnd;
        }
    }

    // Returns true if there is any word in the trie that starts with the given prefix.
    public boolean startsWith(String prefix) {
        TrieNode node = searchNode(prefix);

        if (node == null) {
            return false;
        } else {
            return true;
        }
    }

    // Returns the node that corresponds to the last character in 's', else null.
    public TrieNode searchNode(String s) {
        TrieNode node = root;

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (node.children[c - 'a'] != null) {
                node = node.children[c - 'a'];
            } else {
                return null;
            }
        }

        return node;
    }
}