最近在看tire树,用java实现了个简单的tire树,判断单词的频率
public class TireNode {
private char c;
private int cnt = 0;
private boolean isFinal = false;
private Map<Integer, TireNode> children;
/**
* Getter method for property <tt>c</tt>.
*
* @return property value of c
*/
public int getC() {
return c;
}
/**
* Setter method for property <tt>c</tt>.
*
* @param c value to be assigned to property c
*/
public void setC(char c) {
this.c = c;
}
/**
* Getter method for property <tt>cnt</tt>.
*
* @return property value of cnt
*/
public int getCnt() {
return cnt;
}
/**
* Setter method for property <tt>cnt</tt>.
*
* @param cnt value to be assigned to property cnt
*/
public void setCnt(int cnt) {
this.cnt = cnt;
}
/**
* Getter method for property <tt>children</tt>.
*
* @return property value of children
*/
public Map<Integer, TireNode> getChildren() {
return children;
}
/**
* Setter method for property <tt>children</tt>.
*
* @param children value to be assigned to property children
*/
public void setChildren(Map<Integer, TireNode> children) {
this.children = children;
}
/**
* Getter method for property <tt>isFinal</tt>.
*
* @return property value of isFinal
*/
public boolean isFinal() {
return isFinal;
}
/**
* Setter method for property <tt>isFinal</tt>.
*
* @param isFinal value to be assigned to property isFinal
*/
public void setFinal(boolean isFinal) {
this.isFinal = isFinal;
}
public class TestTire {
public static void main(String[] args) {
String a1 = "abc";
String a2 = "abcd";
String a3 = "ab";
String a4 = "abc";
Map<String, Integer> cnts = new HashMap<String, Integer>();
TireNode tree = new TireNode();
tree.setChildren(new HashMap<Integer, TireNode>());
cnts.put(a1, addNode(a1, tree));
cnts.put(a2, addNode(a2, tree));
cnts.put(a3, addNode(a3, tree));
cnts.put(a4, addNode(a4, tree));
System.out.println(cnts);
}
/**
*
* @param str
* @param tree
*/
private static Integer addNode(String str, TireNode tree) {
Map<Integer, TireNode> children = tree.getChildren();
Integer cnt = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
Integer key = Integer.valueOf(c);
TireNode node = new TireNode();
node.setC(c);
node.setCnt(1);
node.setChildren(new HashMap<Integer, TireNode>());
if (i == str.length() - 1) {
node.setFinal(true);
}
if (children.get(key) == null) {
children.put(key, node);
} else if (i == str.length() - 1 && children.get(key).isFinal() == true) {
children.get(key).setCnt(children.get(key).getCnt() + 1);
} else if (i == str.length() - 1 && children.get(key).isFinal() == false) {
children.get(key).setFinal(true);
}
if (i == str.length() - 1) {
cnt = (children.get(key).getCnt());
}
children = children.get(key).getChildren();
}
return cnt;
}
}