我正在尝试查找存储在 trie 中的所有键,这些键是字符串的有效前缀。
示例:给定一个包含“ab”、“abc”、“abcd”、“bc”和“bcd”的trie。在 trie 中搜索字符串“abcdefg”应得到“abcd”、“abc”、“ab”。
我想为 java 使用 appache commons patricia trie 实现,但它似乎不支持这种查找。是否有任何替代实现或简单的解决方案来解决这个问题?
我正在尝试查找存储在 trie 中的所有键,这些键是字符串的有效前缀。
示例:给定一个包含“ab”、“abc”、“abcd”、“bc”和“bcd”的trie。在 trie 中搜索字符串“abcdefg”应得到“abcd”、“abc”、“ab”。
我想为 java 使用 appache commons patricia trie 实现,但它似乎不支持这种查找。是否有任何替代实现或简单的解决方案来解决这个问题?
我自己没有使用过 Apache Commons PatriciaTrie,但据我检查,您可以轻松地仅获得以某些字符串为前缀的单词映射。我发现的大多数示例还提供了插入、查找等基本操作。我还遇到了一些关于在 guava 中实现 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);
}
}