[Acwing Algorithm Basis] 2.6 Trie Tree

Trie tree application scenarios

  1. Data structure for efficiently storing and looking up collections of strings

Trie Tree Ideas

The idea is shown in the following example. It is obvious that there is no need to describe it in words.

An example of a Trie tree

insert image description here

core code

  1. Storage of Trie Trees
const int N = 1e5 + 10;
int son[N][26]; // 其中存放的是:子节点对应的idx。其中son数组的第一维是:父节点对应的idx,第第二维计数是:其直接子节点('a' - '0')的值为二维下标。
int cnt [N];    // cnt数组记录对应字符串出现的次数
int idx;        // 将该字符串分配的一个树结构中,以下标来记录每一个字符的位置。方便之后的插入和查找。
char str[N];
  1. insert code

insert image description here

void insert(char str[])
{
    
    
    int p = 0;
    for (int i = 0; str[i]; ++i)
    {
    
    
        int u = str[i] - 'a';
        
        // 如果p点不存在u这个子节点则创建
        if (!son[p][u]) son[p][u] = ++idx;
        // 令p等于trie树的叶节点对应的位置
        p = son[p][u];
    }
    
    
    ++cnt[p];
}
  1. query code
int query(char str[])
{
    
    
    int p = 0;
    for (int i = 0; str[i]; ++i)
    {
    
    
        int u = str[i] - 'a';
        if (!son[p][u]) return 0;
        p = son[p][u];
    }
    
    // 返回单次数量
    return cnt[p];
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326133491&siteId=291194637