繁体   English   中英

用于在文本Java中搜索单词的最有效的数据结构

[英]Most efficient data structure for searching for a word in text Java

我有一个程序,可以读取文档并在每个页面中搜索给定的搜索词。 然后返回单词出现在哪些页面。

即单词“辉煌”出现在以下页面中:1,4,6,8

目前,我将文件拆分为页面并将其存储到ArrayList中。 ArrayList的每个元素都包含文档的一页

然后,我将页面上的每个单词拆分并存储到hashMap中,其中KEY是该单词出现在文本中的位置(其他功能我需要知道),而value是该单词。 然后,我使用来搜索HashMap;

if (map.containsValue(searchString) == true)
                return true;
             else
                 return false;

我为每个PAGE执行此操作。

一切正常,但我想知道是否可以使用更有效的数据结构来存储给定页面上所有单词以及页面上出现的位置?(因为在地图中搜索值而没有给出键为0(n))。

我需要能够搜索这种结构并找到一个单词。 请记住,我还需要该职位以备后用。

我使用文本中单词位置填充地图的代码是:

    // text is the page of text from a document as a string
int key = 1; // position of the word in the text
    for (String element : text.split(" "))
            {
                map.put(key, element);
                key++;
            }

为什么不只使用一个将单词映射到出现HashMap<String,ArrayList<Position>> 文本中的每个单词都是地图中的一个键,页码和位置将构成条目列表。

由于列表值,插入有些棘手:

ArrayList<Position> positions = words.get(word);
if (positions == null) {
  positions = new ArrayList<Position>();
  words.put(word, positions);
}
positions.add(position);

或者,您可以使用Guava Multimap: http ://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html(尤其是如果您已经将Guava用于其他目的-我可能会避免为此而引入库依赖项)

编辑 :将整数更改为位置(并将其设置为列表),却忽略了需要确切的位置。 位置应类似于

class Position {
  int page;
  int index; 
}

我可能会自己使用LuceneGuava集合中的某种东西,但是除非我认为最有效的结构是:

HashMap<String, TreeMap<Integer, TreeSet<Integer>>> words;

        ^^^^^^          ^^^^^^^          ^^^^^^^
         word            page            position

使用words.get("brilliant").keySet(); 会立即为您提供“辉煌”出现的所有页面。 如果我没记错的话,那是O(log n)而不是O(n)

阅读完注释后,您还需要在每个搜索词的前后检索该词,我认为您需要用于查找的第二个数据结构:

TreeSet<Integer, TreeMap<Integer, String>> positions;

        ^^^^^^^          ^^^^^^^  ^^^^^^
         page            position  word

或者,也可以使用两个列表的相应索引作为页面和位置:

ArrayList<ArrayList<String>> positions;          

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM