java - 在 Map 实现中搜索前缀的最佳方法是什么?

标签 java string dictionary data-structures

LinkedHashMap.put("a.a1","11");        
LinkedHashMap.put("a.a12","12");        
LinkedHashMap.put("b.b1","13");        
LinkedHashMap.put("c.c1","14");        
LinkedHashMap.put("c.c1","15");          

搜索“a”。键应返回两个值。

我们应该使用 Java 中的哪种数据结构,因为 Trie DS 实现不可用。我能想到的下一个最好的就是 LinkedHashMap

最佳答案

您正在寻找 Apache Patricia Trie .它是您的用例的确切数据结构。

来自他们的文档:

A PATRICIA Trie is a compressed Trie. Instead of storing all data at the edges of the Trie (and having empty internal nodes), PATRICIA stores data in every node. This allows for very efficient traversal, insert, delete, predecessor, successor, prefix, range, and select(Object) operations. All operations are performed at worst in O(K) time, where K is the number of bits in the largest item in the tree. In practice, operations actually take O(A(K)) time, where A(K) is the average number of bits of all items in the tree.

Most importantly, PATRICIA requires very few comparisons to keys while doing any operation. While performing a lookup, each comparison (at most K of them, described above) will perform a single bit comparison against the given key, instead of comparing the entire key to another key.

特别是 prefixMap(prefix) operation返回一个 SortedMap View ,其中包含与给定前缀匹配的所有条目。

同样,来自文档:

For example, if the Trie contains 'Anna', 'Anael', 'Analu', 'Andreas', 'Andrea', 'Andres', and 'Anatole', then a lookup of 'And' would return 'Andreas', 'Andrea', and 'Andres'.

关于java - 在 Map 实现中搜索前缀的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35365979/

相关文章:

c++ - wchar_t* 到字符串的转换

Java网站解析器

c++ - 通过运算符重载写入映射的内容

python - 在 Python 中,动态分配字典条目

使用 logback 的 java.security.policy 问题

java - 线程和同步示例

java - 使用 Java 处理来自 postgreSQL 的大量数据

java - 如何将我的表单与操作链接起来?

c++ - 在 std::string 中仅将数字转换为 int

java - 更新 mongo 抛出 ConcurrentModificationException?