首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Java兑现字典树

2012-08-01 
Java实现字典树package D0726public class T {public static void main(String[] args) {String[] str

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];    }}

热点排行