ITeye博客

java

rfv1116 · 2012-02-09 23:35 · java基础 · 字符串匹配 · 编程语言 · Markdown

看看性能!加载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, ws);
        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() + "");
}

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)

暂无评论。

评论功能维护中,当前仅展示历史评论。