Given strings s1 and s2, determine whether s3 is formed by interleaving s1 and s2 while preserving their original order.
Initially I tried simulation, but there is a problem: what if s1[p1] and s2[p2] are both equal to s3[p3]? In that case, we would need to save state and perform a search.
As expected, it timed out.
I found online that DP can be used:
f[i][j] = f[i-1][j] + s1[i] && s1[i] == s3[k]
f[i][j] = f[i][j-1](i+j = k) && s2[j] == s3[j]
The k-th character in s3 is fully matched only when it equals either the i-th character of s1 or the j-th character of s2.
Enumerate all cases, at most n^2.
Output f[i][j] where i = s1.length(), j = s2.length(), and i+j = s3.length().
| |