Solution: Interleaving Strings
Explore various approaches to solve the interleaving strings problem in detail.
We'll cover the following...
Solution 1: Brute force
using System;class Program{/// <summary>/// Determines if the third string is an interleaving of the first two strings./// </summary>/// <param name="m">First string.</param>/// <param name="n">Second string.</param>/// <param name="p">Third string to check for interleaving.</param>/// <param name="mIndex">Index in the first string.</param>/// <param name="nIndex">Index in the second string.</param>/// <param name="pIndex">Index in the third string.</param>/// <returns>True if the third string is an interleaving of the first two strings, otherwise False.</returns>public static bool FindStringsInterleavingRecursive(string m, string n, string p, int mIndex, int nIndex, int pIndex){// If we have reached the end of all the stringsif (mIndex == m.Length && nIndex == n.Length && pIndex == p.Length)return true;// If we have reached the end of 'p' but 'm' or 'n' still has some characters leftif (pIndex == p.Length)return false;bool b1 = false;bool b2 = false;if (mIndex < m.Length && m[mIndex] == p[pIndex]){b1 = FindStringsInterleavingRecursive(m, n, p, mIndex + 1, nIndex, pIndex + 1);}if (nIndex < n.Length && n[nIndex] == p[pIndex]){b2 = FindStringsInterleavingRecursive(m, n, p, mIndex, nIndex + 1, pIndex + 1);}return b1 || b2;}/// <summary>/// Determines if the third string is an interleaving of the first two strings./// </summary>/// <param name="m">First string.</param>/// <param name="n">Second string.</param>/// <param name="p">Third string to check for interleaving.</param>/// <returns>True if the third string is an interleaving of the first two strings, otherwise False.</returns>public static bool FindStringsInterleaving(string m, string n, string p){return FindStringsInterleavingRecursive(m, n, p, 0, 0, 0);}// Driver code to test the above methodpublic static void Main(string[] args){Console.WriteLine(FindStringsInterleaving("abd", "cef", "adcbef"));Console.WriteLine(FindStringsInterleaving("abc", "def", "abdccf"));Console.WriteLine(FindStringsInterleaving("abcdef", "mnop", "mnaobcdepf"));}}
Explanation
The problem follows the longest common subsequence pattern.
A basic brute force solution is to try matching m
and n
with p
one letter at a time. Let’s assume mIndex
, nIndex
, and pIndex
represent the current indexes of m
, n
, and p
strings, respectively. Therefore, we have two options at any step:
- If the letter at
mIndex
matches the letter atpIndex
, we can recursively match for the remaining lengths of