006字符串查找---基于三向单词查找树的符号表

本文参考《算法(第4版)》

基于三向单词查找树的符号表

1.实现代码

基于三向单词查找树的符号表

package algorithms.stringrank;

public class TST<Value> {
	private Node root;
    class Node{
    	char c;
    	Node left, mid, right;
    	Value val;
    }
    public Value get(String key){
    	Node x = get(root, key, 0);
    	if(x == null) return null;
    	return x.val;
    }
    private Node get(Node x, String key, int d){
    	if(x == null) return null;
    	char c = key.charAt(d);
    	if(c < x.c)      return get(x.left, key, d);
    	else if(c > x.c) return get(x.right, key, d);
    	else if(d < key.length()-1) //key.length()-1是尾字符索引
    	    return get(x.mid, key, d+1); 
    	else return x;      //匹配键的每个字符且达到字符串末尾
    }
    
    public void put(String key, Value val){
    	root = put(root, key, val, 0);
    }
    private Node put(Node x, String key, Value val, int d){ 
    	char c = key.charAt(d);
    	if(x == null) {x = new Node(); x.c = c;}
    	if(c < x.c)      x.left = put(x.left, key, val, d);
    	else if(c > x.c) x.right = put(x.right, key, val, d);
    	else if(d < key.length()-1)
    		  x.mid = put(x.mid, key, val, d+1);
    	else  x.val = val;
    	return x;  //返回根节点
    }
    
    public static void main(String[] args){
    	TST<Integer> tst = new TST<Integer>();
    	tst.put("shells", 0);
    	tst.put("bike", 1);
    	tst.put("shert", 3);
    	tst.put("air", 4);
    	tst.put("book", 5);
    	tst.put("the", 6);
    	tst.put("airby", 7);
    	tst.put("bool", 8);
    	System.out.println(tst.get("book"));
    	System.out.println(tst.get("airby"));
    }
}

输出:
5
7
## 2.总结
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值