📜  后缀树应用程序3 –最长重复子串

📅  最后修改于: 2021-04-17 12:58:12             🧑  作者: Mango

给定一个文本字符串,在文本中找到最长重复子字符串。如果有多个“最长重复子串”,请获取其中任何一个。

Longest Repeated Substring in GEEKSFORGEEKS is: GEEKS
Longest Repeated Substring in AAAAAAAAAA is: AAAAAAAAA
Longest Repeated Substring in ABCDEFG is: No repeated substring
Longest Repeated Substring in ABABABA is: ABABA
Longest Repeated Substring in ATCGATCGA is: ATCGA
Longest Repeated Substring in banana is: ana
Longest Repeated Substring in abcpqrabpqpq is: ab (pq is another LRS here)

这个问题可以通过具有不同时间和空间复杂性的不同方法来解决。在这里,我们将讨论后缀树方法(第三后缀树应用程序)。其他方法将很快讨论。

作为前提,我们必须知道如何以一种或另一种方式构建后缀树。
在这里,我们将使用Ukkonen算法构建后缀树,该算法已在下面进行了讨论:
Ukkonen的后缀树构造–第1部分
Ukkonen的后缀树构造–第2部分
Ukkonen的后缀树构造–第3部分
Ukkonen的后缀树构造–第4部分
Ukkonen的后缀树构造–第5部分
Ukkonen的后缀树构造–第6部分

让我们看下图:
后缀树应用

这是字符串“ ABABABA $”的后缀树。
在此字符串,重复以下子字符串:
A,B,AB,BA,ABA,BAB,ABAB,BABA,ABAB
最长重复子串是ABABA。
在后缀树中,一个节点不能有多个以相同字符开头的输出边缘,因此,如果文本中有重复的子字符串,它们将在同一路径上共享,并且后缀树中的该路径将经过一个或多个树下的内部节点(在该路径上子字符串结束的点下方)。
在上图中,我们可以看到

  • 带有子字符串“ A”的路径在树的下方具有三个内部节点
  • 带有子字符串“ AB”的路径在树的下方有两个内部节点
  • 带有子字符串“ ABA”的路径在树的下方有两个内部节点
  • 带有子字符串“ ABAB”的路径在树下有一个内部节点
  • 带有子字符串“ ABABA”的路径在树下有一个内部节点
  • 带有子字符串“ B”的路径在树的下方有两个内部节点
  • 带有子字符串“ BA”的路径在树的下方有两个内部节点
  • 带有子字符串“ BAB”的路径在树下有一个内部节点
  • 带有子字符串“ BABA”的路径在树下有一个内部节点

重复以上所有子字符串。

子字符串ABABAB,ABABABA,BABAB,BABABA在树中没有内部节点(在路径上子字符串结尾的点之后),因此不会重复。

您能看到如何找到最长的重复子串吗?
我们可以从图中看到,最长的重复子字符串将终止于离根最远的内部节点(即树中最深的节点),因为子字符串的长度是从根到该内部节点的路径标签长度。

因此,找到最长的重复子字符串归结为找到后缀树中最深的节点,然后获得从根到该最深内部节点的路径标签。

// A C program to implement Ukkonen's Suffix Tree Construction
// And then find Longest Repeated Substring
#include 
#include 
#include 
#define MAX_CHAR 256
   
struct SuffixTreeNode {
    struct SuffixTreeNode *children[MAX_CHAR];
   
    //pointer to other node via suffix link
    struct SuffixTreeNode *suffixLink;
   
    /*(start, end) interval specifies the edge, by which the
     node is connected to its parent node. Each edge will
     connect two nodes,  one parent and one child, and
     (start, end) interval of a given edge  will be stored
     in the child node. Lets say there are two nods A and B
     connected by an edge with indices (5, 8) then this
     indices (5, 8) will be stored in node B. */
    int start;
    int *end;
   
    /*for leaf nodes, it stores the index of suffix for
      the path  from root to leaf*/
    int suffixIndex;
};
   
typedef struct SuffixTreeNode Node;
   
char text[100]; //Input string
Node *root = NULL; //Pointer to root node
   
/*lastNewNode will point to newly created internal node,
  waiting for it's suffix link to be set, which might get
  a new suffix link (other than root) in next extension of
  same phase. lastNewNode will be set to NULL when last
  newly created internal node (if there is any) got it's
  suffix link reset to new internal node created in next
  extension of same phase. */
Node *lastNewNode = NULL;
Node *activeNode = NULL;
   
/*activeEdge is represeted as input string character
  index (not the character itself)*/
int activeEdge = -1;
int activeLength = 0;
   
// remainingSuffixCount tells how many suffixes yet to
// be added in tree
int remainingSuffixCount = 0;
int leafEnd = -1;
int *rootEnd = NULL;
int *splitEnd = NULL;
int size = -1; //Length of input string
   
Node *newNode(int start, int *end)
{
    Node *node =(Node*) malloc(sizeof(Node));
    int i;
    for (i = 0; i < MAX_CHAR; i++)
          node->children[i] = NULL;
   
    /*For root node, suffixLink will be set to NULL
    For internal nodes, suffixLink will be set to root
    by default in  current extension and may change in
    next extension*/
    node->suffixLink = root;
    node->start = start;
    node->end = end;
   
    /*suffixIndex will be set to -1 by default and
      actual suffix index will be set later for leaves
      at the end of all phases*/
    node->suffixIndex = -1;
    return node;
}
   
int edgeLength(Node *n) {
    if(n == root)
        return 0;
    return *(n->end) - (n->start) + 1;
}
   
int walkDown(Node *currNode)
{
    /*activePoint change for walk down (APCFWD) using
     Skip/Count Trick  (Trick 1). If activeLength is greater
     than current edge length, set next  internal node as
     activeNode and adjust activeEdge and activeLength
     accordingly to represent same activePoint*/
    if (activeLength >= edgeLength(currNode))
    {
        activeEdge += edgeLength(currNode);
        activeLength -= edgeLength(currNode);
        activeNode = currNode;
        return 1;
    }
    return 0;
}
   
void extendSuffixTree(int pos)
{
    /*Extension Rule 1, this takes care of extending all
    leaves created so far in tree*/
    leafEnd = pos;
   
    /*Increment remainingSuffixCount indicating that a
    new suffix added to the list of suffixes yet to be
    added in tree*/
    remainingSuffixCount++;
   
    /*set lastNewNode to NULL while starting a new phase,
     indicating there is no internal node waiting for
     it's suffix link reset in current phase*/
    lastNewNode = NULL;
   
    //Add all suffixes (yet to be added) one by one in tree
    while(remainingSuffixCount > 0) {
   
        if (activeLength == 0)
            activeEdge = pos; //APCFALZ
   
        // There is no outgoing edge starting with
        // activeEdge from activeNode
        if (activeNode->children] == NULL)
        {
            //Extension Rule 2 (A new leaf edge gets created)
            activeNode->children] =
                                          newNode(pos, &leafEnd);
   
            /*A new leaf edge is created in above line starting
             from  an existng node (the current activeNode), and
             if there is any internal node waiting for it's suffix
             link get reset, point the suffix link from that last
             internal node to current activeNode. Then set lastNewNode
             to NULL indicating no more node waiting for suffix link
             reset.*/
            if (lastNewNode != NULL)
            {
                lastNewNode->suffixLink = activeNode;
                lastNewNode = NULL;
            }
        }
        // There is an outgoing edge starting with activeEdge
        // from activeNode
        else
        {
            // Get the next node at the end of edge starting
            // with activeEdge
            Node *next = activeNode->children];
            if (walkDown(next))//Do walkdown
            {
                //Start from next node (the new activeNode)
                continue;
            }
            /*Extension Rule 3 (current character being processed
              is already on the edge)*/
            if (text[next->start + activeLength] == text[pos])
            {
                //If a newly created node waiting for it's 
                //suffix link to be set, then set suffix link 
                //of that waiting node to current active node
                if(lastNewNode != NULL && activeNode != root)
                {
                    lastNewNode->suffixLink = activeNode;
                    lastNewNode = NULL;
                }
  
                //APCFER3
                activeLength++;
                /*STOP all further processing in this phase
                and move on to next phase*/
                break;
            }
   
            /*We will be here when activePoint is in middle of
              the edge being traversed and current character
              being processed is not  on the edge (we fall off
              the tree). In this case, we add a new internal node
              and a new leaf edge going out of that new node. This
              is Extension Rule 2, where a new leaf edge and a new
            internal node get created*/
            splitEnd = (int*) malloc(sizeof(int));
            *splitEnd = next->start + activeLength - 1;
   
            //New internal node
            Node *split = newNode(next->start, splitEnd);
            activeNode->children] = split;
   
            //New leaf coming out of new internal node
            split->children] = newNode(pos, &leafEnd);
            next->start += activeLength;
            split->children] = next;
   
            /*We got a new internal node here. If there is any
              internal node created in last extensions of same
              phase which is still waiting for it's suffix link
              reset, do it now.*/
            if (lastNewNode != NULL)
            {
            /*suffixLink of lastNewNode points to current newly
              created internal node*/
                lastNewNode->suffixLink = split;
            }
   
            /*Make the current newly created internal node waiting
              for it's suffix link reset (which is pointing to root
              at present). If we come across any other internal node
              (existing or newly created) in next extension of same
              phase, when a new leaf edge gets added (i.e. when
              Extension Rule 2 applies is any of the next extension
              of same phase) at that point, suffixLink of this node
              will point to that internal node.*/
            lastNewNode = split;
        }
   
        /* One suffix got added in tree, decrement the count of
          suffixes yet to be added.*/
        remainingSuffixCount--;
        if (activeNode == root && activeLength > 0) //APCFER2C1
        {
            activeLength--;
            activeEdge = pos - remainingSuffixCount + 1;
        }
        else if (activeNode != root) //APCFER2C2
        {
            activeNode = activeNode->suffixLink;
        }
    }
}
   
void print(int i, int j)
{
    int k;
    for (k=i; k<=j; k++)
        printf("%c", text[k]);
}
   
//Print the suffix tree as well along with setting suffix index
//So tree will be printed in DFS manner
//Each edge along with it's suffix index will be printed
void setSuffixIndexByDFS(Node *n, int labelHeight)
{
    if (n == NULL)  return;
   
    if (n->start != -1) //A non-root node
    {
        //Print the label on edge from parent to current node
        //Uncomment below line to print suffix tree
       // print(n->start, *(n->end));
    }
    int leaf = 1;
    int i;
    for (i = 0; i < MAX_CHAR; i++)
    {
        if (n->children[i] != NULL)
        {
            //Uncomment below two lines to print suffix index
           // if (leaf == 1 && n->start != -1)
             //   printf(" [%d]\n", n->suffixIndex);
   
            //Current node is not a leaf as it has outgoing
            //edges from it.
            leaf = 0;
            setSuffixIndexByDFS(n->children[i], labelHeight +
                                  edgeLength(n->children[i]));
        }
    }
    if (leaf == 1)
    {
        n->suffixIndex = size - labelHeight;
        //Uncomment below line to print suffix index
        //printf(" [%d]\n", n->suffixIndex);
    }
}
   
void freeSuffixTreeByPostOrder(Node *n)
{
    if (n == NULL)
        return;
    int i;
    for (i = 0; i < MAX_CHAR; i++)
    {
        if (n->children[i] != NULL)
        {
            freeSuffixTreeByPostOrder(n->children[i]);
        }
    }
    if (n->suffixIndex == -1)
        free(n->end);
    free(n);
}
   
/*Build the suffix tree and print the edge labels along with
suffixIndex. suffixIndex for leaf edges will be >= 0 and
for non-leaf edges will be -1*/
void buildSuffixTree()
{
    size = strlen(text);
    int i;
    rootEnd = (int*) malloc(sizeof(int));
    *rootEnd = - 1;
   
    /*Root is a special node with start and end indices as -1,
    as it has no parent from where an edge comes to root*/
    root = newNode(-1, rootEnd);
   
    activeNode = root; //First activeNode will be root
    for (i=0; isuffixIndex == -1) //If it is internal node
    {
        for (i = 0; i < MAX_CHAR; i++)
        {
            if(n->children[i] != NULL)
            {
                doTraversal(n->children[i], labelHeight +
                                edgeLength(n->children[i]), maxHeight,
                                 substringStartIndex);
            }
        }
    }
    else if(n->suffixIndex > -1 && 
                (*maxHeight < labelHeight - edgeLength(n)))
    {
        *maxHeight = labelHeight - edgeLength(n);
        *substringStartIndex = n->suffixIndex;
    }
}
  
void getLongestRepeatedSubstring()
{
    int maxHeight = 0;
    int substringStartIndex = 0;
    doTraversal(root, 0, &maxHeight, &substringStartIndex);
//    printf("maxHeight %d, substringStartIndex %d\n", maxHeight,
//           substringStartIndex);
    printf("Longest Repeated Substring in %s is: ", text);
    int k;
    for (k=0; k

输出:

Longest Repeated Substring in GEEKSFORGEEKS$ is: GEEKS
Longest Repeated Substring in AAAAAAAAAA$ is: AAAAAAAAA
Longest Repeated Substring in ABCDEFG$ is: No repeated substring
Longest Repeated Substring in ABABABA$ is: ABABA
Longest Repeated Substring in ATCGATCGA$ is: ATCGA
Longest Repeated Substring in banana$ is: ana
Longest Repeated Substring in abcpqrabpqpq$ is: ab
Longest Repeated Substring in pqrpqpqabab$ is: ab

在多个LRS的情况下(正如我们在过去两年的测试案例看),这种实现打印,其配备1按字典的LRS。

Ukkonen的后缀树构造需要O(N)的时间和空间来构建长度为N的字符串的后缀树,之后找到最深的节点将花费O(N)。
因此,它在时间和空间上是线性的。

后续问题:

  1. 查找给定文本中的所有重复子字符串
  2. 查找给定文本中的所有唯一子字符串
  3. 查找给定长度的所有重复子串
  4. 查找给定长度的所有唯一子字符串
  5. 如果文本中有多个LRS,请查找出现次数最多的那个

所有这些问题都可以在线性时间内解决,而在上述实现中只需很少改动即可解决。

我们已经发布了更多有关后缀树应用程序的文章:

  • 后缀树应用程序1 –子字符串检查
  • 后缀树应用程序2 –搜索所有模式
  • 后缀树应用程序4 –构建线性时间后缀数组
  • 广义后缀树1
  • 后缀树应用程序5 –最长公共子串
  • 后缀树应用6 –最长回文子串