DEV Community

faangmaster
faangmaster

Posted on

Реализация префиксного дерева(Trie) на Java

class Trie {
    TrieNode root;

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

    public void insert(String word) {
        TrieNode current = root;
        for (char c : word.toCharArray()) {
            if (!current.children.containsKey(c)) {
                current.children.put(c, new TrieNode());
            }
            current = current.children.get(c);
        }
        current.terminates = true;
    }

    public boolean search(String word) {
        TrieNode current = root;
        for (char c : word.toCharArray()) {
            if (!current.children.containsKey(c)) {
                return false;
            }
            current = current.children.get(c);
        }
        return current.terminates;
    }

    public boolean startsWith(String prefix) {
        TrieNode current = root;
        for (char c : prefix.toCharArray()) {
            if (!current.children.containsKey(c)) {
                return false;
            }
            current = current.children.get(c);
        }
        return true;
    }

    class TrieNode {
        Map<Character, TrieNode> children;
        boolean terminates;

        public TrieNode() {
            this.children = new HashMap<>();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)