基于单词查找树的符号表
这种方法其实也很简单,我们把每个节点都设置256个子节点,然后将字符串往里面插入就行了
template<typename V>
class trie
{
private:
const static int r = 256;
struct node
{
V value;
node next[r];
} *root;
node *get(node *x, std::string key, int d)
{
if (x == nullptr)
return nullptr;
if (d == key.length())
return x;
char c = key[d];
return get(x->next[d], key, d + 1);
}
node *put(node *x, std::string key, V value, int d)
{
if (x == nullptr)
{
x = new node;
}
if (d == key.length())
{
x->value = value;
return x;
}
char c = key[d];
x->next[c] = put(x.next[c], key, value, d + 1);
return x;
}
public:
V get(std::string key)
{
node *x = get(root, key, 0);
if (x == nullptr)
return NULL;
return x->value;
}
void put(std::string key, V value)
{
root = put(root, key, value, 0);
}
};
基于三向查找树的符号表
关于三向xxx我们已经遇到很多了,相信你一看就能明白什么意思
template<typename V>
class TST
{
private:
struct node
{
char c;
node *left, *right, *mid;
V value;
} *root;
node *get(node *x, std::string key, int d)
{
if (x == nullptr)
return nullptr;
char c = key[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)
return get(x->mid, key, d + 1);
else
return x;
}
node *put(node x, std::string key, V value, int d)
{
char c = key[d];
if (x == nullptr)
{
x = new node;
x->c = c;
}
if (c < x->c)
x->left = put(x->left, key, value, d);
else if (c > x->c)
x->right = put(x->right, key, value, d);
else
x->value = value;
return x;
}
public:
V get(std::string key)
{
node *x = get(root, key, 0);
if (x == nullptr)
return NULL;
return x->value;
}
void put(std::string key, V value)
{
root = put(root, key, value, 0);
}
};
值得注意的是,虽然单词查找树符号表比起三向查找树符号表要矮很多,这就意味着要更快,但是我们同时也必须注意到单词查找树的复杂难以整理及其浪费的大量内存。我个人是更倾向于使用第二种方法的
|