java

看看性能!加載15萬多個詞,搜索不到1毫秒。 不知和ZZL算法比如何

Load dict in 1273 ms, size=157202
Search pattern: 中國
Searched in 1 ms.
Map size=389[,中國,中國上海,中國專利,中國專利局,...]

Search pattern: abc
Searched in 0 ms.
Map size=0[]

Search pattern: 電子
Searched in 0 ms.
Map size=130[,電子,電子世界,電子樂器,電子書,電子書下載,...]

Search pattern: 中
Searched in 0 ms.
Map size=1147[,中上,中上層,中上游,中下,中下層,...]


Java code

public class TreeMapTest {
private SortedMap<String,String> words = new TreeMap<String,String>();

public TreeMapTest(String[] args){
for(String s:args){
words.put(s, s);
}
}

public TreeMapTest(String dict) throws Exception{
long start = System.currentTimeMillis();
File in = new File(dict);
BufferedReader reader = new BufferedReader(new FileReader(in));
String line = reader.readLine();
while(null != line){
String[] ws = line.split("\t");
words.put(ws[0], ws[0]);
line = reader.readLine();
}
reader.close();
long end = System.currentTimeMillis();
System.out.println("Load dict with " + (end-start) + " ms, size=" + words.size());
}

public void search(String pattern){
System.out.println("Search pattern: " + pattern);
long start = System.currentTimeMillis();
String fromKey = pattern;
String toKey = null;
int length = pattern.length();
if( length == 1){
toKey = String.valueOf((char)(pattern.charAt(0)+1));
}else{
StringBuilder sb = new StringBuilder();
sb.append(pattern.substring(0, length-1));
sb.append((char)(pattern.charAt(length-1)+1));
toKey = sb.toString();
}
SortedMap<String,String> result = words.subMap(fromKey, toKey);
long end = System.currentTimeMillis();
System.out.println("Searched in " + (end-start) + " ms.");
show(result);
}

public void show(SortedMap<String,String> map){
System.out.println("Map size=" + map.size() + "[");
Set<String> keys = map.keySet();
for(String key:keys){
System.out.print(",");
System.out.print(key);
}
System.out.println("]");
}

public static void main(String[] args) throws Exception {
// String[] strs = {"abc","ab","d","abcde","da","db","dbc","ac","aca","中國","中華人民共和國","中國人","中國龍"};
// TreeMapTest test = new TreeMapTest(strs);
TreeMapTest test = new TreeMapTest("your dict file");


test.search("中國");
test.search("abc");
test.search("電子");
test.search("中");
}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章