Interleaving String in C++


Suppose we have three strings s1, s2 and s3. Then check whether s3 is formed by interleaving s1 and s2 or not. So if the strings are “aabcc”, s2 = “dbbca”, and s3 is “aadbbcbcac”, then the result will be true.

To solve this, we will follow these steps −

  • Define one method called solve(), this will take s1, s2, s3 and one 3d array dp, then i, j, k

  • if i = 0 and j = 0 and k = 0, then return true

  • if dp[i, j, k] is not -1, then return dp[i, j, k]

  • ans := false

  • if j > 0 and k >= 0 and s2[j] = s3[k], then

    • ans := solve(s1, s2, s3, dp, i – 1, j, k – 1)

  • if j > 0 and k >= 0 and s2[j] = s3[k], then

    • ans := ans OR solve(s1, s2, s3, dp, i, j – 1, k – 1)

  • set dp[i, j, k] := ans

  • return dp[i, j, k]

  • From the main method, do the following −

  • n := size of s1, m := size of s2, o := size of s3

  • Add one blank space before s1, s2, s3.

  • make one array of size (n + 1) x (m + 1) x (o + 1), fill this with -1

  • return solve(s1, s2, s3, dp, n, m, o)

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool solve(string s1, string s2, string s3, vector < vector < vector <int>>>& dp, int i, int j, int k){
      if(i ==0 && j == 0 && k == 0)return true;
      if(dp[i][j][k] !=-1)return dp[i][j][k];
      bool ans = false;
      if(i > 0 && k >= 0 && s1[i] == s3[k]){
         ans = solve(s1, s2, s3, dp, i - 1, j, k - 1);
      }
      if(j >0 && k >=0 && s2[j] == s3[k]){
         ans |= solve(s1, s2, s3, dp, i, j - 1, k - 1);
      }
      return dp[i][j][k] = ans;
   }
   bool isInterleave(string s1, string s2, string s3) {
      int n = s1.size();
      int m = s2.size();
      int o = s3.size();
      s1 = " " + s1;
      s2 = " " + s2;
      s3 = " " + s3;
      vector < vector < vector <int>>> dp(n + 1, vector < vector <int>>(m + 1, vector <int> (o + 1, -1)));
      return solve(s1, s2, s3, dp, n , m , o );
   }
};
main(){
   Solution ob;
   cout << (ob.isInterleave("aabcc", "dbbca", "aadbbcbcac"));
}

Input

"aabcc", "dbbca", "aadbbcbcac"

Output

1

Updated on: 26-May-2020

325 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements