仅纯数字的前缀树Java实现

备忘。


/*
 * 前缀树
 * key是纯数字的字符串
 * */
@SuppressWarnings({"unchecked", "rawtypes"})
public class NumericStringTireMap<T> {

  public static class Node<T> {
    private final Node[] data = new Node[10];
    private T value;
  }

  private final Node root;

  public NumericStringTireMap() {
    root = new Node<T>();
  }

  public void put(String key, T value) {
    Node current = root;
    for (char c : key.toCharArray()) {
      int idx = c - '0';
      if (current.data[idx] == null) {
        current.data[idx] = new Node<T>();
      }
      current = current.data[idx];
    }
    current.value = value;
  }

  public T prefixMatch(String key) {
    Node current = root;
    Object result = null;
    for (char c : key.toCharArray()) {
      int idx = c - '0';
      if (current.data[idx] == null) {
        break;
      }
      current = current.data[idx];
      if (current.value != null) {
        result = current.value;
      }
    }
    return (T) result;
  }

}

 

posted @ 2025-02-20 22:18  Jackie_JK  阅读(13)  评论(0)    收藏  举报