Java 查找patricia trie中作为字符串前缀的所有键

Java 查找patricia trie中作为字符串前缀的所有键,java,apache-commons,trie,patricia-trie,Java,Apache Commons,Trie,Patricia Trie,我试图查找存储在trie中的所有键,这些键是字符串的有效前缀 例如: 给定包含“ab”、“abc”、“abcd”、“bc”和“bcd”的trie。在trie中搜索字符串“abcdefg”应产生“abcd”、“abc”、“ab” 我想使用appache commons patricia trie的java实现,但它似乎不支持这种查找。这个问题有没有其他的实现或简单的解决方案 我自己没有使用apachecommons PatriciaTrie,但据我所查,您可以很容易地得到前缀为字符串的单词映射。我

我试图查找存储在trie中的所有键,这些键是字符串的有效前缀

例如: 给定包含“ab”、“abc”、“abcd”、“bc”和“bcd”的trie。在trie中搜索字符串“abcdefg”应产生“abcd”、“abc”、“ab”


我想使用appache commons patricia trie的java实现,但它似乎不支持这种查找。这个问题有没有其他的实现或简单的解决方案

我自己没有使用apachecommons PatriciaTrie,但据我所查,您可以很容易地得到前缀为字符串的单词映射。我发现的大多数示例还提供了一些基本操作,如insert、find。我还遇到了一些关于在guava中实现Trie的讨论,但没有具体的内容

因此,这里是我对自定义实现的简单建议(但在使用自定义实现时,应该包含一组良好的测试)

公共类SimpleTrie{
私有静态最终整数字母计数=26;
类三节点{
字符值;
三元组[]儿童;
布尔值;
三节点(){
这(“”);
}
三节点(字符值){
这个值=值;
儿童=新三元组[字母表计数];
isValidWord=false;
}
}
私有三节点根=新三节点();
公共空白插入(字符串字){
三极电流=根;
for(int i=0;i
谢谢您的回复!我可能会将该方法添加到commons实现中,而不是从头开始重新实现trie。只是想在开始任何冒险之前先问一下。
public class SimpleTrie {

    private static final int ALPHABET_COUNT = 26;

    class TrieNode {
        char value;
        TrieNode[] children;
        boolean isValidWord;

        TrieNode() {
            this(' ');
        }

        TrieNode(char value) {
            this.value = value;
            children = new TrieNode[ALPHABET_COUNT];
            isValidWord = false;
        }
    }

    private TrieNode root = new TrieNode();

    public void insert(String word) {
        TrieNode current = root;

        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);

            if (current.children[c - 'a'] == null) {
                current.children[c - 'a'] = new TrieNode(c);
            }

            current = current.children[c - 'a'];
        }

        current.isValidWord = true;
    }

    public List<String> findValidPrefixes(String word) {
        List<String> prefixes = new ArrayList<>();
        TrieNode current = root;

        StringBuilder traversedPrefix = new StringBuilder();

        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);

            if (current.children[c - 'a'] != null) {
                current = current.children[c - 'a'];
                traversedPrefix.append(c);

                if (current.isValidWord) {
                    prefixes.add(traversedPrefix.toString());
                }
            }
        }

        return prefixes;
    }

    public static void main(String[] args) {
       SimpleTrie trie = new SimpleTrie();

        // insert "ab", "abc", "abcd", "bc" and "bcd"
        trie.insert("ab");
        trie.insert("abc");
        trie.insert("abcd");
        trie.insert("bc");
        trie.insert("bcd");

        List<String> validPrefixes = trie.findValidPrefixes("abcdefg");

        System.out.println(validPrefixes);
    }
}