java 版字典树

来源:互联网 发布:电脑分屏镜像软件 编辑:程序博客网 时间:2024/05/07 09:03
public class Main {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, "sdf")) {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];}}


原创粉丝点击