string: KMP eentend-kmp automaton trie graph trie tree suffix tree suffix array
2009-09-25 00:00:40| Classification: Algorithms and ACM| Report | Font size subscription
Problems related to strings, no matter how many algorithms and data structures: automata KMP algorithm extend-kmp suffix tree suffix array trie tree trie graph and its application. Of course these are relatively advanced data structures and algorithms, and the most commonly used and most familiar is the KMP, even though there are still a considerable part of the people do not understand KMP, let alone other. Of course the general string problem, we just use simple brute force algorithm can be solved, and then if the violent efficiency is too low, we use a hash. Of course, Hash is also an interview often used in the method. In this way, some of these algorithms and data structures are rarely asked, but if you use them generally you can get a good linear complexity algorithm.
Frankly speaking, I have always felt that the string problem is very complicated, out of a if the use of violence, hash, it is difficult to think of other methods, of course, some can use dynamic planning. But in order to solve this persistent problem, we have carefully studied these algorithms and data structures. Make a note lest you forget to think about it for a long time. If you encounter string problems, they generally do not exceed the scope of these methods. Let's take a look at the diagram, and explain the relationship between the data structures of these algorithms. The yellow part of the figure mainly describes some key points of these algorithms and data structures.
These relationships can be seen in the figure: EXTEND-KMP is an extension of the KMP; AC automata is a multi-string form of KMP; it is a finite automaton, whereas the trie diagram is actually a deterministic finite automata; AC automata, trie graphs, suffix trees are actually a kind of trie suffix arrays and suffix trees are data structures related to the suffix collection of strings; the suffix pointer in the trie diagram and the suffix link in the suffix tree are both concepts and their consistency.
We will explain these algorithms and data structures separately, and analyze and explain the key issues involved.
Kmp
First the matching algorithm, the main idea is to make full use of the previous match results, find the matching failure, the pattern string can move forward the maximum distance. This maximum distance must be guaranteed not to miss a possible matching position, so the maximum distance is actually the next array value of the current matching position of the pattern string. That is, Max{aj is the Pi suffix J < I},pi, which indicates that the string A[1...i],aj represents A[1...J]. The next array calculation of the pattern string is a self-matching process. is also the process of calculating next[i] using the existing value next[1...i-1]. We can see that if a[i] = a[next[i-1]+1] then next[i] = next[i-1], otherwise, you can continue to move the pattern string forward.
The whole process is this:
void Next_comp (char * str) {
int next[n+1];
int k = 0;
NEXT[1] = 0;
Cyclic invariance, start of each cycle, k = next[i-1]
for (int i = 2; I <= N; i++) {
If the current position does not match, or if it is pushed to the beginning of the string, continue pushing
while (a[k+1]! = a[i] && k! = 0) {
k = Next[k];
}
if (a[k+1] = = A[i]) k++;
Next[i] = k;
}
}
Complexity analysis: From the above process can be seen, the internal cycle of the continuous execution of k = Next[k], and this value is necessarily in the reduction, that is, the K is not executed at least 1, on the other hand, the initial value of K is 0, and a maximum of + + n times, and K is always non-negative, it is obvious that the So the complexity of the whole process is O (N).
The above is the calculation of the next array, and the entire KMP matching process is similar.
Extend-kmp
Why is it called extension-KMP, first we look at what it calculates, it is the longest public prefix that asks for the suffix of string b and the length of string A. Extend[i] means b[i ... B_len] The longest public prefix length of a, that is, the array to be computed.
By observing this array, KMP can tell if a is a substring of B and find the first matching position? For extend[] arrays, it can be used to solve the matching problem directly, as long as the extend[] array element is equal to len_a. Obviously, this array holds more and richer information, that is, the matching length of each position of B with a.
The calculation of this array extend also uses a similar process for KMP. The first is also the longest common prefix length that needs to be computed for string A and its own suffix. We set it to next[] array. Of course, here the next array of meanings and KMP in the process. But its calculations, also using the already calculated next[1...i-1] to find the size of next[i], the whole idea is the same.
This is exactly the case: observation can reveal
First in 1...i-1, to find a k, make it meet k+next[k]-1 maximum, that is, let K plus next[k] length as long as possible.
In fact, the following proof process is the use of each calculation after the k+next[k] always only increase, and it is clearly an upper bound, to prove the complexity of the entire computational process is linear. As shown, suppose we have found such a k and then see how to calculate the value of next[i]. Set len = k+next[k]-1 (We use AK on behalf of Next[k]) and discuss it in the following cases:
If Len < I that is, Len's length is not covered to AI, so we just start from the beginning to compare A[I...N] and a the longest public prefix can, in this case, it is obvious that each comparison, will inevitably let i+next[i]-1 add one.
If Len >= i is what we are expressing in the diagram, then we can see that the position of I is now equal to the element in the position of I-k+1, which in two cases
If L = next[i-k+1] >= len-i+1, that is, L is in the position of the second dashed line, so that we can see the size of the next[i], at least len-i+1, and then we start from here to compare whether the later can match, obviously if more than once, also let i+ A[i]-1 increased 1 more.
If L < len-i+1 means L is in the first dashed position, we know that a and AK match in this position, but AK and ai-k+1 do not match in this position, obviously a and ai-k+1 in this position will not match, so next[i] is the value of L.
So the value of next[i] is calculated, from the above process we can see, next[i] can either be directly from the position of k, or need to be compared, but if you need to compare, each comparison will let k+next[k]- The maximum value of 1 plus 1. And the whole process of this value only increases, and it has a very obvious upper bound k+next[k]-1 < 2*len_a, the number of visible comparisons to be limited to this value, so the total complexity will be O (N).
Trie Tree
First the trie tree is actually a character lookup tree of some strings, and the edges are represented by the characters that represent the strings, so that we can determine in O (Len (str)) whether a string belongs to that collection. The branches within the trie tree can also be implemented by using a list of links, each with its own merits and demerits.
Simple trie tree each edge is represented by one character, but in order to save space, you can make the edge represent a paragraph of characters, which is the compression representation of trie. The compression representation can make the spatial complexity of trie proportional to the number of word nodes.
AC Automatic Machine
AC automata, which can be seen as KMP in multi-string cases, can be used to handle multi-pattern string matching. Just create a trie tree for these pattern strings, and then create a failed pointer for each node, that is, the next function like with KMP, and let us know where to start again if the match fails. AC actually two names of the initials of the person, Aho-corasick.
It should be remembered that when KMP constructs the next array, we construct it in the past, i.e. construct the 1...i-1 first and then use them to calculate next[i], which is similar here. But this successively, is through the BFS the order to embody. The failure pointer of AC automaton has the same function, that is, when our pattern string matches on tire, if the keyword of the current node cannot continue to match, we should go to the node where the current node's failure pointer points to continue to match. The string from the root to the node that the failed pointer points to is actually the longest string that matches the suffix of the current node.
The process is as follows:
--------------Reference: AC (Aho-corasick) automaton algorithm http://hi.baidu.com/luyade1987/blog/item/5ba280828dcb9eb96d811972.html
Like a pattern string in KMP. Starting from the root node, for each node: Set the node to the character K, along its father node to the failure of the pointer to go, until the root nodes or the current failed pointer node is also the existence of the character K son node,
The former case, of course, is to set the failure pointer to the root node, and the latter to the current failed pointer node has the character K son node.
We can also do this, if our AC automaton contains only a single pattern string, this process is actually a KMP calculation process.
The next thing to do is to match the text:
First, trie-(the collection of pattern strings) has a pointer P1 to root, and a pointer p2 to the string header in the text string. The following actions are similar to KMP: if you set K to the letter P2 points to, and the node P1 points to in Trie has a son with the character K, then P2++,P1
Instead, point to the son whose character is K, otherwise the P1 follows the current node's failed pointer up until P1 has a son whose character is K, or P1 points to the root node. If P1 passes a node marked as the end of the pattern string, then the pattern at the end of this point
The string has already been matched. Or if the point where the P1 is located can follow the failed pointer to the end of a pattern string, then the pattern string ending with that node has already been matched.
The relevant information can be found in the following links:
Www.cs.uku.fi/~kilpelai/BSA05/lectures/slides04.pdf
It mainly constructs three functions goto fail and output according to the pattern string.
Q: = 0; Initial state (Root)
For I: = 1 to M do
While G (Q, t[i]) = 0 Do
Q: = f (q); Follow a fail
Q: = g (q, T[i]); Follow a goto
If out (q)! = 0; Then print I, out (q);
ENDfor;
-----------------------------------------End of reference---------------------------------------------------------------------------- ---------------
Take Ababa as an example, we can get its KMP next array value of 0 0 1 2 3,ac automata and trie diagram as follows:
Trie Chart
The trie diagram is actually a deterministic automaton, which increases the certainty of this property than AC, and for AC automata it may take several backtracking times to make the next match after encountering a mismatched node. However, for trie graphs, each step can be matched one at a time, and there is a certain state node for each input character encountered.
From the above figure we can also see that the suffix node of the trie graph is basically the same as the suffix pointer of the AC automaton, except that the root of the trie diagram is added to the edges of all character sets. In addition, the trie graph also complements the edges of the characters in all character sets for each node, and this process of trimming is actually the process of finding the node's suffix node, but these nodes are virtual, we don't add them to the graph, we find their equivalent nodes, their suffix nodes, This allows these sides to refer to the suffix node. (for example, in the Black node C, it does not actually appear in our initial tire, but we can treat it as a virtual node, pointing its edge to its suffix node)
The trie chart mainly uses two concepts to achieve this purpose. One is the suffix node, which is the path string for each node that removes the node corresponding to the first character string. The method of calculating this node is through the suffix node of its Father node, it is obvious that the difference between its father's suffix node and its suffix node is that there is less one tail character, set to C. So the node's parent node's pointer to the C child is the node's suffix node. But because sometimes his father does not necessarily have C children, so he has to find a father's C child equivalent node. So we have a problem of finding the equivalent node.
And the trie graph also has a complement operation, the non-existent character corresponding to the edge point of the node can actually be regarded as a virtual node, we want to find an existing and its equivalent node, the edge point to it. This also actually seeks to find the equivalent node.
We see how to find the equivalent node of a node, our so-called equivalence refers to their risk consistency. Let's look at one more. The necessary and sufficient condition for a node to be a dangerous node is that its path string itself is a dangerous word, or its path string suffix corresponds to a node that is a dangerous node. So we can see that if the path string of the node is not a dangerous word in itself, then it is equivalent to its suffix node. So when we make up the edge, the actual point is the node suffix node can be.
The trie diagram actually improved the trie tree and added additional information. It makes it easy to solve the problem of multi-mode string matching. Like KMP's ideas, the trie chart also wants to take advantage of the information that has now been matched to provide guidance for future matches. Some new concepts are proposed. Defines a string of characters Fulianqi on all sides of a path from the root to a node on the trie tree, called the path string of the node. If a node's path string ends with a dangerous string, the node is a dangerous node: that is, if reaching this point represents a matching state; otherwise it is a security node. So how can you tell if a node is dangerous?
The root node is clearly a security node. The necessary and sufficient condition for a node to be a dangerous node is that its path string itself is a dangerous word, or the suffix of its path string (in this case, a string that removes the remainder of the first character) corresponding to the node (a string corresponding to the node, which refers to the root node in the trie diagram start, A node that arrives at the edge specified by a character, in turn, is a dangerous node.
So how do you ask for each node's suffix node? Here you can use the previous calculation information to get it. In particular, using the suffix node of the Father node, we just remember that the last word of the current node subscript character C, then the parent node's suffix node C branch node is the required suffix node. First of all, we limit the root node of the suffix node is the root, the first node of the suffix node is the Roots node. This allows us to find out the suffix nodes of all nodes, step by layer. However, there may be a problem in this process: the suffix node of the Father node may not have a C branch. What should I do now?
As shown if the suffix node of the parent node of the current node is W, we assume that W has a C child for, and we can see that for the entire C subtree of W, because there is no edge C to them at all, they cannot be bad strings, so that the risk of these nodes is equivalent to the risk of their suffix nodes, And their suffix node, actually is the suffix node of the C child, so back down, and finally can be found.
--------------------References: http://huangwei.host7.meyu.net/?paged=7
In fact, the role of Trie map is to establish a deterministic finite automaton DFA, each point in the graph is a state, the transition between states with a edges representation. Trie figure is on the basis of tire, in fact, he should be regarded as the derivation of AC automata, AC automata only save the suffix node, in use, and then use Postfix node to jump, and has been iterative to find the corresponding state transfer, this should be considered KMP thought. This article can be consulted.
The trie chart directly saves the AC automaton's value in the current node after the state transfer calculation, making it unnecessary to iterate over the suffix nodes. So each node of the trie graph has |∑| state transitions (∑ refers to the character set). Construction concrete method can be seen WC2006 "the construction, utilization and improvement of Trie map". I briefly describe the following process:
(1) Build trie, and ensure that the root node must have |∑| son.
(2) Hierarchy traversal trie, compute suffix node, node tag, no |∑| son of the complement edge.
Calculation of the suffix node:
(1) The suffix node of the root junction is itself.
(2) The suffix node in the second layer of the trie tree is also the root junction point.
(3) The suffix node of the remaining node is the node with the corresponding state transfer in the suffix node of its parent node (this is analogous to the iterative process of AC automata).
Node Tag:
(1) There is a mark in itself.
(2) The suffix node is marked.
Margin:
The corresponding state transfer of the suffix node is used to fill the blank of the current node.
At last, any node in the Trie graph has the corresponding state transfer, we use this state transfer to do dynamic programming.
Set DP[I][J] indicates that the first state produces J-characters, the minimum change value with the DNA sequence.
Assuming that the root node in the tire diagram is 0, the dp[0][0]=1 is initialized.
Thereafter, the BFS traversal of the diagram shows that at the level J, it is indicated that a J-length string is generated.
Dp[0][0] = 1;for i = 1 to M does a for graph each edge (S1,CH,S2) do dp[s2][i] = Min{dp[s1][i-1] + (txt[i-1]! = ch)}; For each node in the for graph x do ans = min{dp[x][m]};
-----------------------------------------------End of reference---------------------------------------------------------------------- -------------
Suffix tree
A suffix tree, which is actually a collection of strings consisting of all the suffixes of a string trie tree. If the trie storage is uncompressed, the sum of the entire internal node and the external node is likely to reach O (n^2). So you can't take advantage of this storage, because if you use it then the complexity of building the lower bound is O (n^2), no less. Therefore, it is necessary to use the compression method, which can be reduced to O (n).
Before we build, we first add a word to the string that is not in the string, such as "$", why did you do it? is to avoid the suffix node in the interior, if we add "$", it is obvious that there will be no suffix in the interior, you can prove with contradiction: assuming that a suffix like this is an internal node, then it means that the string path will have two "$", but this is not possible, because our "$" Appears only at the end and has not been seen before.
In the construction process, we look at what it would be like to use a common build process. Normal construction, assuming that the string is A[1....N], we start with a suffix beginning with a[1] to insert the trie tree, when inserted, step-by-point, until a mismatched branch is found, where the node splits the original node and joins the new node. The key to this process is to look for the longest public prefix of these already inserted strings with Sufix[i], before Sufix[1]...sufix[i-1]. The time that is inserted after O (1) can be completed, so the main time is spent on the search for the longest common prefix (called Head[i]). The Headi is the longest public prefix of W (i,n) and W (J,n), where j is any positive integer less than I, and Taili makes Headi + Taili = W (i,n).
Then we see that the key now is the longest public prefix head[i] calculation. We again consider how to use head[1]...head[i-1] to calculate head[i], in order to speed up the search for hi, we need to use the auxiliary structure--suffix link.
Definition of suffix link (mccreight arithmetic):
Make head[i-1] = AZ, where a is the i-1 character of the string W. Because Z appears at least two times within the range I (because AZ is also a[i-1 ... N] The longest public prefix of a previous suffix, which means that the other suffix is also a string at the beginning of the AZ, which means that its successor is more than the z prefix, so a[i ... N] and its public prefix is Z. {This property is actually used when we compute the LCP of the suffix array), so there must be | head[i]| >= |z|,z is the prefix for Head[i]. The so-called hi-1 suffix link (Suffix link) is actually a pointer to z corresponding to node D by hi-1 Link h[i-1]. Of course, z may be an empty string, when link hi-1 is directed by Hi-1 to root.
And the previous AC automata failed pointer trie tree suffix Pointer comparison, we can find here Z it is just head[i-1] remove the suffix after the first character, so-called suffix link, is actually a link to the suffix of head[i] itself, This definition is consistent with the position pointed to by the suffix pointer in our trie tree. It is clear how the suffix link of this head[i] is built.
To create a method:
1) root node suffix link to itself
2) any suffix link for a non-leaf node is created immediately after the node appears
The main framework of the algorithm is as follows:
For i = 1-n Do
Step 1, function find from link hi-1 start down Search for node hi
Step 2, add leaf node Leafi
Step 3, function down create the suffix link hi
End for
Suffix Tree Performance Analysis:
Then just the pseudo-code inside the text box to talk about. For a given I, the complexity of Step 2 is O (1), but because the number of nodes between link hi-1 to hi cannot be determined, step 1 is not guaranteed to be linear. Local estimate failure, may wish to start from the whole. One thing is for sure, that is i + | Headi| always increases with the increment of I. Therefore, each character in W will only be traversed 1 times by the Find function, and the overall complexity is O (n).
This analysis is similar to the EXTEND-KMP complexity analysis.
Suffix array
The suffix array is actually the suffix of the string sorted by dictionary order, and then placed in the order of the sequence in an array sa[], the array element represents the suffix in the original string of the starting index. By this we can easily get another array rank[],rank[i] representing the original suffix a[i ... N] The rank in the SA array.
This data structure, mainly related to two aspects of the content, one is how to quickly sort these suffixes, there are many methods, here only to explain the multiplication algorithm, this method is relatively good understanding, thinking is also more ingenious.
There is the suffix array to find out, if you want to play a more powerful role, but also require the suffix of the longest common prefix LCS. So the calculation of LCS is also a key point.
First look at the sort, if we use the ordinary sorting algorithm, then need NLOGN comparison, but each comparison needs O (n), so the total complexity will be O (N*NLOGN).
The multiplication algorithm is this, mainly the first order, the comparison when the size of the use of the i-1 order results, so that the comparison in O (1) Time to complete:
We first sort all the characters with a length of 1 starting at each position of the original string, and then a sort of length of 2 from those positions, followed by a sort of length of 2^i, until 2^i >= N. You can see this in the middle, a total of log n order. Then we look at the first order, how to compare the size of the use of the first i-1 order results.
For example, in the first order, we need to compare a[j] and A[k] to start with a string of length 2^i, then we can divide them into two pieces:
A[J] Start i-1 (a[j+2^) Length of 2^ (i-1) long + 2^ (i-1)] beginning with 2^i string = A[j]
A[k] Start i-1 (a[k+2^) Length of 2^ (i-1) long + 2^ (i-1)] beginning with 2^i string = A[k]
To compare A[j] starts with a string of length 2^i and A[k] starts with a string of 2^i, we simply compare the first part, such as equality and then the 2nd part, and the two part size because it has been ordered before, we can give them a rank value, The size relationship can be obtained only by comparing their rank values so that the comparison can be done in O (1) time. In addition, if our sorting algorithm is O (n), then the complexity of the whole algorithm is O (NLOGN).
Looking at the LCS calculation, if you want to calculate any of the two suffixes of lcs[i][j], we have a conclusion:
Set I<j LCP (I,J) =MIN{LCP (k-1,k) |i+1 =< k <= J} LCP theorem here i,j refers to Sa[i] sa[j]
If you want to prove the above conclusion, first of all to prove this: to arbitrary 1=<i<j<k<=n, LCP (i,k) =MIN{LCP (i,j), LCP (J,k)}, here is no longer proof.
The above conclusion actually says: If you want to find the longest common prefix length of i j, I just need to find the minimum LCS length of the adjacent suffix between I j. So we just need to ask for the length of the LCS of the adjacent suffix in the SA array, which translates into a RMQ problem, the minimum value problem in the interval. This can be solved by O (1). So the question becomes: how to calculate the length of the LCS in an O (n) time in the adjacent suffix of the SA array.
If you want O (n), use the following conclusion: Define a one-dimensional array height, make HEIGHT[I]=LCP (i-1,i) 1<i<=n and set height[1]=0. How to calculate the height array as efficiently as possible?
To describe the convenience, set h[i]=height[rank[i]], i.e. height[i]=h[sa[i]], and the H array satisfies a property:
For i>1 and rank[i]>1 must have h[i] >= h[i-1]-1.
Why do you have this conclusion? In fact, the suffix link to the suffix tree above is the part of the reference to echo. H[i]=height[rank[i]], is actually our original suffix a[i ... N] The longest public prefix of a string, while H[i-1] is a[i-1 ... N] The longest public prefix to a string. And we can see if the a[i-1 ... N] After the first character is removed, it becomes a a[i ... N], we assume that a[i-1 ... N] The adjacent suffix string is xyyyyyy, where the length of the LCS is h[i]. Suffix string xyyyyyy, minus X is yyyyyyy, so if there is no closer than it a[i ... N], then h[i]=h[i-1]-1, if A[i ... N] The neighbor is not it, then h[i] can only be smaller than the h[i-1]-1 larger than it.
Using this conclusion, we can calculate the h[i in O (n) time. Because H[i] is no more than N, and it is reduced by up to 1 at a time.
After calculating, then according to Height[i]=h[sa[i]], you can calculate the height array, so that the adjacent suffix of the SA length of the LCS.
Summarize:
In fact, we can see the above algorithm idea, all have one thing in common: the results of the next calculation are obtained by using the calculated results obtained, and the calculation amount is reduced by using the existing information as far as possible.
Reprint please specify [email protected] Source: http://duanple.blog.163.com/blog/static/709717672009825004092/
2016-08-19 11:37:20
"Turn" a large summary of various string algorithms