读书人

Java兑现字典树

发布时间: 2012-08-01 17:53:40 作者: rapoo

Java实现字典树

package D0726;public class T {    public static void main(String[] args) {        String[] str = { "asdf", "asji", "bjkl", "cdsdf", "jdsfk" };        Trie root = new Trie();        for (String s : str) {            insert(root, s);        }        if (find(root, "asdf")) {            System.out.println("string is found~");        } else {            System.out.println("not found~");        }    }    public static void insert(final Trie root, String str) {        Trie cur = root;        for (char ch : str.toCharArray()) {            int idx = ch - 'a';            if (cur.child[idx] == null) {                cur.child[idx] = new Trie();            }            cur = cur.child[idx];            cur.ch = ch;        }    }    public static boolean find(final Trie root, String str) {        Trie cur = root;        for (char ch : str.toCharArray()) {            int idx = ch - 'a';            if (cur.child[idx] == null) {                return false;            }            cur = cur.child[idx];        }        return true;    }}class Trie {    Trie[] child;    char ch;    public Trie() {        child = new Trie[26];    }}

读书人网 >编程

热点推荐