[英]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;
}
我可能會自己使用Lucene或Guava集合中的某種東西,但是除非我認為最有效的結構是:
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.