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

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

  • 本文参考《算法(第4版)》
  • 基于三向单词查找树的符号表
    • 1.实现代码

本文参考《算法(第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.总结
 

你可能感兴趣的:(笔记)