For example,
Given:
s1 =
"aabcc"
,s2 =
"dbbca"
,
When s3 =
"aadbbcbcac"
, return true.When s3 =
"aadbbbaccc"
, return false.Solution
This is another perfect problem to practice Dynamic Programming.My thoughts:
Firstly I oversimplified the problem. Thought it might work by iterate through s3 to match a letter either in S1 or S2. Of course it is wrong. Anti-example: s1= aa, s2=ab, s3=aaba.
Then I realized it can be solved with recursion. The implementation is as follows:
However, it failed on large test cases in leetcode.
Naturally I resorted to DP. The typical way of solving a problem with DP is to find the state, and the optimal function. Here, the state can be considered as: dp[i][j] meaning S3[i+j] can be formed by S1[i] and S2[j] (for simplicity here string starts from 1, in the code we need to deal with that string starts from 0). With the recursion code as in lines 43~47, it is easy to come up with the optimal function:
dp[i][j]=(dp[i-1][j]==true && s1.charAt(i-1)==s3.charAt(i+j-1))
||(dp[i][j-1]==true && s2.charAt(j-1)==s3.charAt(i+j-1) )
Note: the initial states require great care to populate as well as the index. See the code:
To run the code in your mind, simply use s1="a", s2="b", s3="ab" as an example.
No comments:
Post a Comment