双阵列尝试问题

Double-Array Trie Question

本文关键字:问题 阵列      更新时间:2023-10-16

我试图从 http://linux.thai.net/~thep/datrie/datrie.html 中理解双阵列Trie实现但我不明白以下部分。

check[base[s] + c] = s
base[s] + c = t 

在这里添加c是什么意思。

任何人都可以用简单的语言解释算法。

假设您将一个 2D 数组折叠成一个 1D 数组:

int arr2D[2][3];
int arr1D[2 * 3]; // # of rows * # of columns
// access element [1][2] of 2D array, i.e., the last element
int elem2D = arr2D[1][2];
// access element [1][2] of 1D array, i.e., the last element
int elem1D = arr1D[1 * 3 + 2];
// =========================================================
lets visualize the array access:
arr2D => x/y 0  1  2
          0 [N][N][N]
+1 on x > 1 [N][N][N]
+2 on y ---------- ^
y_len  =>   ^-------^ 3 elements
so the access happens with x * y_len + y
                           1 *   3   + 2
now for the 1D array
we want the second row, so we go with 1 * 3
(0-based access, y_len = 3)
and then we want the 3rd element, so + 2
(again, 0-based access)
arr1D =>  x  0  1  2 
            [N][N][N]
             3  4  5
1 * 3 = 3 > [N][N][N]
      + 2 = 5 ---- ^

我希望我没有把这件事变得太复杂(即使我认为我做到了...... :)

字符

是"从零开始的",即"a"是0,"b"是1,"c"是2,等等。 查找"a"意味着将该 0 添加到当前节点的基址并检查该索引的所有者。 如果该所有者是当前节点,则 trie 中当前节点中有一个以"a"开头的字符串,该索引处的基址是下一次查找的基址。

应将代码编辑为以下内容:

check[base[s] + c] = s
next[base[s] + c] = t 

在状态s接受字符c并转换为状态t的场景中:s - c -> t 。关键是base[s]意味着什么。由于一个州可以接受多个字符:

| |c1|c2|c3||--|--|--|--||S|x|Y|Z|问题在于你如何表达这些s-c1->xs-c2->ys-c3->z的映射。传统上,map是一种很好的做法:

class State {
    Map<Character, State> mappings;
}

但是,如果您使用数组来表达映射呢? base[s] 是数组next基索引,从中添加偏移量cbase[s] + cnext 中的最后一个索引,用于存储从状态s和字符c映射的下一个状态。请注意,字符c实际上是编程语言中的整数。