字典树

package com.xiaomi.mahout_test;

public class Trie {
private Node root;

public Trie() {
root = new Node();
}

public static void addWord(Node root, String sentence) {
Node cur = root;
for (char tmp : sentence.toCharArray()) {
int index = tmp - 'a';
if (cur.chlidrens[index] == null) {
cur.chlidrens[index] = new Node();
}
cur = cur.chlidrens[index];
cur.ch = tmp;
}
}
public static boolean findWord(Node root, String sentence) {
Node cur = root;
for (char tmp : sentence.toCharArray()) {
int index = tmp - 'a';
if (cur.chlidrens[index] == null) {
return false;
}
cur = cur.chlidrens[index];
}
return true;
}
public static void main(String[] args) {
String[] str = {"asdf", "asji", "bjkl", "cdsdf", "jdsfk"};
Trie trie = new Trie();
for (String s : str) {
addWord(trie.root, s);
}
if (findWord(trie.root, "jdsfk")) {
System.out.println("string is found~");
} else {
System.out.println("not found~");
}
}
static class Node {
Node[] chlidrens = new Node[26];
char ch;
}
}

posted @ 2015-08-11 15:29  glose  阅读(253)  评论(1编辑  收藏  举报