Nine-chapter algorithm surface question 36 staggered string

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.