Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java文本中搜索单词最有效的数据结构_Java_Search_Hashmap - Fatal编程技术网

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

在Java文本中搜索单词最有效的数据结构,java,search,hashmap,Java,Search,Hashmap,我有一个程序,它读取一个文档,并在每一页上搜索给定的搜索词。然后返回单词出现在哪个页面 i、 e.“辉煌”一词出现在以下页面:1、4、6、8 此时,我将文件拆分为多个页面,并将其存储到ArrayList中。 ArrayList的每个元素都包含一页文档 然后,我将页面上的每个单词拆分并存储到hashMap中,关键字是该单词在文本中出现的位置(我需要知道其他功能的位置),值是该单词。然后,我使用 if (map.containsValue(searchString) == true)

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

i、 e.“辉煌”一词出现在以下页面:1、4、6、8

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

然后,我将页面上的每个单词拆分并存储到hashMap中,关键字是该单词在文本中出现的位置(我需要知道其他功能的位置),值是该单词。然后,我使用

if (map.containsValue(searchString) == true)
                return true;
             else
                 return false;
我对每一页都这样做

一切正常,但我想知道是否有一种更有效的数据结构可以用于存储给定页面上的所有单词以及出现在页面上的位置?(因为在地图中搜索值而不提供键是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
?文本中的每个单词都是地图中的一个键,页码和位置将构成条目列表

由于列表值的原因,插入有点棘手:

ArrayList<Position> positions = words.get(word);
if (positions == null) {
  positions = new ArrayList<Position>();
  words.put(word, positions);
}
positions.add(position);
我可能会使用或我自己的东西,但除此之外,我认为最有效的结构是:

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

        ^^^^^^          ^^^^^^^          ^^^^^^^
         word            page            position
或者,使用两个列表的相应索引作为页面和位置:

ArrayList<ArrayList<String>> positions;          
ArrayList位置;

感谢您的回复,您是说将文档存储在hashMap中,字符串是每页上的文本,Set是页码?字符串将是单个单词,整数集将包含该单词出现的页码(我已尝试在回答文本中对此进行了澄清)但是为了计算单词出现的页码,我需要使用与我的原始帖子中类似的算法,这将需要0(n)。我希望避免这种情况,如果可能的话,使用更有效的方法possible@Steve每次搜索文档时都会执行O(n),而不是一次搜索文档。这是一个巨大的区别。这个解决方案中存储的单词的位置在哪里?
TreeSet<Integer, TreeMap<Integer, String>> positions;

        ^^^^^^^          ^^^^^^^  ^^^^^^
         page            position  word
ArrayList<ArrayList<String>> positions;