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

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值