![JAR search and dependency download from the Maven repository](/logo.png)
shz.core.st.tst.LTST Maven / Gradle / Ivy
package shz.core.st.tst;
import shz.core.queue.a.LArrayQueue;
import shz.core.stack.l.LLinkedStack;
import java.util.function.Predicate;
/**
* 值为E类型的TST
*
* 8+[51+E(类型字节)+对齐填充]*n(n为元素个数)
*
* B=24+48*n+(3+E+对齐填充)*n
*/
public class LTST extends TST> {
private static final long serialVersionUID = -1395940341884097354L;
/**
* 8+E(类型字节)+27+对齐填充
*
* B=51+E(类型字节)+对齐填充
*
* 若E为String,则B=41+64+2*n(n为字符串长度)=105+2*n+对齐填充
* 三向单词查找树相比常规单词查找树可节省内存消耗而且不受字母表大小的限制
*/
protected static final class Node extends TST.Node> {
private static final long serialVersionUID = -4847655036854304338L;
public E val;
public Node(char c) {
super(c);
}
}
public static LTST of() {
return new LTST<>();
}
public final void put(char[] a, E val) {
root = put(root, a, val, 0);
}
protected final Node put(Node x, char[] a, E val, int d) {
if (x == null) x = new Node<>(a[d]);
if (a[d] < x.c) x.left = put(x.left, a, val, d);
else if (a[d] > x.c) x.right = put(x.right, a, val, d);
else if (d < a.length - 1) x.mid = put(x.mid, a, val, d + 1);
else {
x.val = val;
x.leaf = true;
}
return x;
}
public final E get(char[] a, int n) {
Node x = get(root, a, n);
return x == null || !x.leaf ? null : x.val;
}
public final E get(char[] a) {
return get(a, a.length);
}
public final LArrayQueue getAll() {
return get(root, false);
}
protected final LArrayQueue get(Node x, boolean prefix) {
LArrayQueue queue = LArrayQueue.of();
if (x != null) {
LLinkedStack> stack = LLinkedStack.of();
if (x.mid != null) stack.push(x.mid);
if (!prefix) {
if (x.left != null) stack.push(x.left);
if (x.right != null) stack.push(x.right);
}
while (!stack.isEmpty()) {
Node pop = stack.pop();
if (pop.leaf) queue.offer(pop.val);
push(stack, pop);
}
}
return queue;
}
private void push(LLinkedStack> stack, Node x) {
if (x.left != null) stack.push(x.left);
if (x.mid != null) stack.push(x.mid);
if (x.right != null) stack.push(x.right);
}
public final LArrayQueue getByPrefix(char[] prefix) {
return get(get(root, prefix, 0), true);
}
public final LArrayQueue getChars(Predicate predicate, int limit) {
return getChars0(x -> predicate == null || predicate.test(x.val), limit);
}
}