Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.9 kB
6
Indexable
Never
class Trie {

    private class TrieNode {
        Map<Character, TrieNode> edges;
        boolean isWordEnd;
        
        TrieNode() {
            this.edges = new HashMap<>();
            isWordEnd = false;
        }
    }

    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }
    
    public void insert(String word) {
        if (word == null || word.isEmpty()) {
            return;
        }

        char[] charArray = word.toCharArray();
        TrieNode current = root;

        for (char c : charArray) {
            if (!current.edges.containsKey(c)) {
                current.edges.put(c, new TrieNode());
            }
            current = current.edges.get(c);
        }

        current.isWordEnd = true;
    }
    
    public boolean search(String word) {
        if (word == null || word.isEmpty()) {
            return true;
        }

        char[] charArray = word.toCharArray();
        TrieNode current = root;
        int count = 0;

        for (char c : charArray) {
            if (current.edges.containsKey(c)) {
                current = current.edges.get(c);
                count++;
            }
        }

        return current.isWordEnd && count == word.length();
    }
    
    public boolean startsWith(String prefix) {
        if (prefix == null || prefix.isEmpty()) {
            return true;
        }

        int count = 0;
        char[] charArray = prefix.toCharArray();
        TrieNode current = root;

        for (char c : charArray) {
            if (current.edges.containsKey(c)) {
                current = current.edges.get(c);
                count++;
            }
        }

        return count == prefix.length();
    }
}

/**
 * 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);
 */
Leave a Comment