java 版字典树

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


你可能感兴趣的:(java,String,null,Class,insert)