"Algorithms that programmers must master" Dictionary tree "Part 1"

"Algorithms that programmers must master" Dictionary tree "Part 1"

Preface: In computer science, a dictionary tree (Trie) is an ordered tree used to store associative arrays (sometimes we call it a "map" or "dictionary"). Unlike a binary search tree, the keys are not stored directly in the nodes, but are determined by the node's position in the tree. The advantage of dictionary trees is that they can find, insert, and delete strings very quickly.

This article will introduce the basic concepts, construction methods and application scenarios of dictionary trees, and explain the application of dictionary trees from shallow to deep through three examples.


basic concept

Dictionary tree is a tree structure, and its typical application is for counting and sorting a large number of strings (but not limited to strings). It is often used by search engine systems for text word frequency statistics.

The following are the basic concepts of dictionary trees:

  • The root node does not contain characters, and each node except the root node contains only one character;
  • From the root node to a certain node, the characters passing on the path are connected to form the string corresponding to the node;
  • All child nodes of each node contain different characters.

Build method

A typical operation of a dictionary tree is to insert a string. We can insert a string according to the following steps:

  • Starting from the root node, find the node where the first character is located;
  • If the corresponding node is found, continue to search for the next character;
  • If the corresponding node is not found, create a new node, link it to the corresponding pointer of the previous node, and continue looking for the next character.

The following is the Java code implementation:

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

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 (char c : word.toCharArray()) {
    
    
            if (node.children[c - 'a'] == null) {
    
    
                node.children[c - 'a'] = new TrieNode();
            }
            node = node.children[c - 'a'];
        }
        node.isWord = true;
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
    
    
        TrieNode node = root;
        for (char c : word.toCharArray()) {
    
    
            if (node.children[c - 'a'] == null) {
    
    
                return false;
            }
            node = node.children[c - 'a'];
        }
        return node.isWord;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
    
    
        TrieNode node = root;
        for (char c : prefix.toCharArray()) {
    
    
            if (node.children[c - 'a'] == null) {
    
    
                return false;
            }
            node = node.children[c - 'a'];
        }
        return true;
    }
}

Application scenarios

The most common application scenario of dictionary trees is string-related problems. The following are three examples to illustrate the application of dictionary trees from shallow to deep:

Example 1: Find words

Given a collection of words (shown below), find whether a word occurs in the collection.

["hello", "world", "leetcode"]

The following is the Java code implementation:

class Solution {
    
    
    public boolean findWord(String[] words, String target) {
    
    
        Trie trie = new Trie();
        for (String word : words) {
    
    
            trie.insert(word);
        }
        return trie.search(target);
    }
}

Example 2: Find word prefixes

Given a collection of words (shown below), find whether a word is a prefix of a word in the collection.

["hello", "world", "leetcode"]

The following is the Java code implementation:

class Solution {
    
    
    public boolean findPrefix(String[] words, String target) {
    
    
        Trie trie = new Trie();
        for (String word : words) {
    
    
            trie.insert(word);
        }
        return trie.startsWith(target);
    }
}

Example 3: Count the number of word prefixes

Given a set of words (shown below), count the number of words starting with a certain prefix.

["hello", "world", "leetcode"]

The following is the Java code implementation:

class TrieNode {
    
    
    public int count;
    public TrieNode[] children = new TrieNode[26];
}

class Trie {
    
    
    private TrieNode root;

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

    public void insert(String word) {
    
    
        TrieNode node = root;
        for (char c : word.toCharArray()) {
    
    
            if (node.children[c - 'a'] == null) {
    
    
                node.children[c - 'a'] = new TrieNode();
            }
            node = node.children[c - 'a'];
            node.count++;
        }
    }

    public int countPrefix(String prefix) {
    
    
        TrieNode node = root;
        for (char c : prefix.toCharArray()) {
    
    
            if (node.children[c - 'a'] == null) {
    
    
                return 0;
            }
            node = node.children[c - 'a'];
        }
        return node.count;
    }
}

class Solution {
    
    
    public int countPrefix(String[] words, String prefix) {
    
    
        Trie trie = new Trie();
        for (String word : words) {
    
    
            trie.insert(word);
        }
        return trie.countPrefix(prefix);
    }
}

In the above code, we use countPrefixthe method to count the number of words starting with a certain prefix.

Summarize

This article introduces the basic concepts, construction methods and application scenarios of dictionary trees, and provides three examples to illustrate the application of dictionary trees from simple to profound. In actual development, the dictionary tree is a very commonly used data structure that can help us solve various string-related problems.

Guess you like

Origin blog.csdn.net/qq_45704048/article/details/132841311