trie树的java实现

一个简单的trie tree数据结构

public class Trie {

static class TrieNode

{

private int count;

private byte c;

private TrieNode[] children;

private int wid=0;

public TrieNode(int width)

{

children=new TrieNode[width];

count=0;

wid=width;

c=(byte)0;

}

public int getCount()

{

return count;

}

public void setCount(int ct)

{

count=ct;

}

public byte getByte()

{

return c;

}

public void setByte(byte b)

{

c=b;

}

public TrieNode[] getChildren()

{

return children;

}

public void setChildren(TrieNode[] nodes)

{

children=nodes;

}

public void add(byte[] bts, int i) {

if(i>=bts.length)

{

this.count++;

}else

{

for(int j=0;j<this.children.length;++j)

{

if(this.children[j]==null)

{

this.children[j]=new TrieNode(wid);

this.children[j].setByte(bts[i]);

this.children[j].add(bts, i+1);

break;

}else if(this.children[j].getByte()==bts[i])

{

this.children[j].add(bts, i+1);

break;

}

}

}

}

public int getCount(byte[] bts, int i) {

if(i>=bts.length)

{

return this.getCount();

}else

{

for(int j=0;j<this.children.length;++j)

{

if(this.children[j]==null)

{

return -1;

}

if(this.children[j].getByte()==bts[i])

{

return this.children[j].getCount(bts,i+1);

}

}

}

return -1;

}

}

private int width;

private TrieNode root;

public Trie(int width)

{

this.width=width;

root=new TrieNode(this.width);

}

public void add(byte[] bts)

{

for(int i=0;i<root.getChildren().length;++i)

{

if(root.getChildren()[i]==null)

{

root.getChildren()[i]=new TrieNode(width);

root.getChildren()[i].setByte(bts[0]);

root.getChildren()[i].add(bts, 1);

break;

}else if(root.getChildren()[i].getByte()==bts[0])

{

root.getChildren()[i].add(bts, 1);

break;

}

}

}

public int getCount(byte[] bts)

{

for(int i=0;i<root.getChildren().length;++i)

{

if(root.getChildren()[i]==null)

{

return -1;

}

if(root.getChildren()[i].getByte()==bts[0])

{

return root.getChildren()[i].getCount(bts, 1);

}

}

return -1;

}

}


 

你可能感兴趣的:(java,trie,cws)