shz.st.triest.JTrieST Maven / Gradle / Ivy
package shz.st.triest;
import shz.queue.JLinkedQueue;
import shz.stack.LLinkedStack;
import java.util.Collections;
import java.util.function.Predicate;
/**
* 值为long类型的基于单词查找树的符号表
*
* 8+24+2*r(r为chars数组长度)=chars
* 8+(56+8*r)*n(n为元素个数)+8*r*n*w(w为键的平均长度)
*
* B=56*(n+1)+8*r*n*(w+1)+(2*r+对齐填充)
*/
public class JTrieST extends TrieST {
/**
* 8+25+8*r(r为数组长度)+对齐填充=40+8*r
*
* B=56+8*r
*/
protected static final class Node extends TrieST.Node {
public long val;
public Node(int r) {
super(r);
}
}
protected JTrieST(char[] chars) {
super(chars);
root = new Node(chars.length);
}
public static JTrieST of(char[] chars) {
if (chars == null || chars.length == 0) throw new NullPointerException();
return new JTrieST(chars);
}
public final void put(char[] a, long val) {
check(a);
Node x = root();
for (char c : a) {
int i = idx(c);
if (x.next[i] == null) x.next[i] = new Node(chars.length);
x = x.next(i);
}
x.val = val;
x.leaf = true;
}
public final Long get(char[] a) {
check(a);
Node x = get(root, a, a.length);
return x == null || !x.leaf ? null : x.val;
}
public final Iterable getAll() {
return get(root());
}
protected final Iterable get(Node x) {
JLinkedQueue queue = JLinkedQueue.of();
LLinkedStack stack = LLinkedStack.of();
push(stack, x);
while (stack.size() > 0) {
Node pop = stack.pop();
if (pop.leaf) queue.offer(pop.val);
push(stack, pop);
}
return queue.isEmpty() ? Collections.emptyList() : queue;
}
private void push(LLinkedStack stack, Node x) {
if (x.next == null) return;
for (int i = 0; i < chars.length; ++i) if (x.next[i] != null) stack.push(x.next(i));
}
public final Iterable getByPrefix(char[] prefix) {
check(prefix);
Node x = get(root, prefix, prefix.length);
if (x == null) return Collections.emptyList();
return get(x);
}
public final Iterable getChars(Predicate predicate, int limit) {
return getChars0(x -> predicate == null || predicate.test(((Node) x).val), limit);
}
}