前言
本博客为系列博客。主要根据的是《算法》forth Edition来写的。在后面的时间会逐渐加上一些题目正文
5.2 单词查找树
public class StringST< Value>
StringST() create a symbol table
void put(String key, Value val) put key-value pair into the table(removekeyif value isnull)
Value get(String key) value paired with key(nullifkey is absent)
void delete(String key) remove key (and its value)
boolean contains(String key) is there a value paired with key?
boolean isEmpty() is the table empty?
String longestPrefixOf(String s) the longest key that is a prefix of s
Iterable<String> keysWithPrefix(String s) all the keys having s as a prefi x
Iterable<String> keysThatMatch(String s) all the keys that match s(where.matches any character)
int size() number of key-value pairs
Iterable<String> keys() all the keys in the table
API for a symbol table with string keys
5.2.1 单词查找树(trie)
5.2.1.1 基本性质
- 父节点:每个节点都有一个指向它的节点。根节点除外。
- R条链接:每个节点有R条链接,R为字母表的大小。
5.2.1.2 单词查找树中的查找操作
- key的尾字符所对应的节点中的Value 非null。这是一次命中查找,key对应的值就是key的尾字符所对应的节点中保存的Value。
- key的尾字符所对应的结点中的Value is null。这是一次未命中查找。
- 查找结束语一条 null link。未命中
5.2.1.3 单词查找树中的插入操作
- 记录查找路径上所找到的最长键的长度。(晕倒值非空的节点时会更新它)
- 查找会在被查找的字符串结束或是遇到null时候终止。
5.2.1.9 删除操作
- 找到key所对应的Node,并将它的值设为空(null)。
- 如果该结点含有一个非空的链接指向某个子节点,那么就不需要再进行其他操作;如果他的所有链接均为null,那么就需要从数据结构中山区这个结点;如果删除同时使得它的父节点的所有链接为null,则需要从数据结构中山区这个Node<递归>。
public void delete(String key){
root = delete(root, key, 0);
}
private Node delete(Node x, String key, int d){
if(x == null) return null;
if(d == key.length())
x.val = null;
else{
char c= key.charAt(d);
x.next[c] = delete(x.next[c], key, d+1);
}
if(x.val != null) return x;
for(char c = 0; c < R; c++)
if(x.next[c] != null)
return x;
return null;
}