Nine Chapters count judges Net-original websitehttp://www.jiuzhang.com/problem/36/
Topics
Given three strings A, B, C, determine if C is staggered by A and B. Interleaving means that for string C, each character can be marked as a Class A or class B, so that each character order of my Class A is a string, and each character order of Class B forms the B string. For example: For a= "Rabbit" b= "MQ", "RABMBITQ" is composed of a and b staggered, but "rabbqbitm" is not composed of a and B staggered.
Answer
Dynamic programming algorithm is adopted. F[I][J] represents the first I character in A, and B takes the first J character, whether it is interleaved with the first i+j characters in C. The state transfer equation is deduced:
F[I][J] = F[i-1][j] && a[i-1] = = C[i+j-1] | | F[I][J-1] && b[j-1] = = C[i+j-1]
Initialize: f[0][i] = B.prefix (i) = = C.prefix (i); F[i][0] = A.prefix (i) = = C.prefix (i);
Both time and space complexity are O (n^2)
Interviewer Angle
The dynamic programming of two sequences (or strings) is a common dynamic planning interview problem, most typically examples such as LCS issues (longest common subsequence) and edit Distance (string editing distance). The representation of the state is similar, all F[i][j] represents the first I character of a string and the first J characters of the B string "match" up. If you understand the problem of LCS, then the topic is essentially just a few simple transformations, the idea is almost identical.
Nine-chapter algorithm surface question 36 staggered string