📜  使用Trie按反向字典顺序打印字符串(1)

📅  最后修改于: 2023-12-03 15:22:21.093000             🧑  作者: Mango

使用 Trie 按反向字典顺序打印字符串

Trie(也称为字典树或前缀树)是一种高效的数据结构,用于存储和快速查询字符串集合。使用 Trie 可以按照字典序,查找和匹配单词等操作。

但是,如果需要按照反向字典序打印字符串集合,该如何实现呢?本文将针对这一问题进行讲解,并提供代码实现。

实现思路

要按照反向字典序打印字符串集合,可以先将字符串集合中的每个字符串进行反转,然后构建一颗 Trie 树,而 Trie 树的每个节点表示一个字符,从根节点到叶子节点的路径表示一个字符串。

最终可以按照反向字典序,遍历 Trie 树,并将遍历到的字符串推入一个栈中,最后将栈中的元素逐一出栈,即可按反向字典序打印字符串集合。

代码实现
Python:
class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_word = False


class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for c in word:
            if c not in node.children:
                node.children[c] = TrieNode()
            node = node.children[c]
        node.is_word = True

    def reverse_print(self):
        stack = []
        self._dfs(self.root, "", stack)
        while stack:
            print(stack.pop())

    def _dfs(self, node, s, stack):
        if node.is_word:
            stack.append(s)
        for c, child in node.children.items():
            self._dfs(child, s+c, stack)

words = ["hello", "world", "leetcode", "trie"]
trie = Trie()
for word in words:
    trie.insert(word[::-1])
trie.reverse_print()
Java:
class TrieNode {
    Map<Character, TrieNode> children;
    boolean isWord;

    public TrieNode() {
        children = new HashMap<>();
        isWord = false;
    }
}

public class Trie {
    TrieNode root;

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

    public void insert(String word) {
        TrieNode node = root;
        for (int i = word.length() - 1; i >= 0; i--) {
            char c = word.charAt(i);
            if (!node.children.containsKey(c)) {
                node.children.put(c, new TrieNode());
            }
            node = node.children.get(c);
        }
        node.isWord = true;
    }

    public void reversePrint() {
        Stack<String> stack = new Stack<>();
        dfs(root, "", stack);
        while (!stack.isEmpty()) {
            System.out.println(stack.pop());
        }
    }

    private void dfs(TrieNode node, String s, Stack<String> stack) {
        if (node.isWord) {
            stack.push(s);
        }
        for (Map.Entry<Character, TrieNode> entry : node.children.entrySet()) {
            char c = entry.getKey();
            TrieNode child = entry.getValue();
            dfs(child, s + c, stack);
        }
    }

    public static void main(String[] args) {
        String[] words = {"hello", "world", "leetcode", "trie"};
        Trie trie = new Trie();
        for (String word : words) {
            trie.insert(new StringBuilder(word).reverse().toString());
        }
        trie.reversePrint();
    }
}
总结

本文介绍了如何使用 Trie 按反向字典序打印字符串集合。实现思路为先将字符串集合中的每个字符串进行反转,然后构建 Trie 树进行遍历,最后将遍历到的字符串推入一个栈中,并将栈中元素逐一出栈,即可按反向字典序打印字符串集合。