欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java,

来源: javaer 分享于  点击 47756 次 点评:111

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("中");
}

}

相关文章

    暂无相关文章
相关栏目:

用户点评