Program to check whether final string can be formed using other two strings or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have two strings s, t, and another string r we have to check whether there is any way to get r by merging characters in order from s and t.

So, if the input is like s = "xyz" t = "mno" r = "xymnoz", then the output will be True, as xymnoz can be formed by interleaving xyz and mno.

To solve this, we will follow these steps −

  • Define a function solve() . This will take s, t, r

  • if s, t and r are empty, then

    • return True

      • if r is empty, then

        • return False

  • if s is empty, then

    • return true when t is same as r, otherwise false

  • if not t is non−zero, then

    • return s is same as r

  • if s[0] is same as r[0], then

    • if solve(s[from index 1 to end], t, r[from index 1 to end]) is true, then

      • return True

  • if t[0] is same as r[0], then

    • if solve(s, t[from index 1 to end], r[from index 1 to end]) is true, then

      • return True

  • return False

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def solve(self, s, t, r):
      if not s and not t and not r:
         return True
      if not r:
         return False
      if not s:
         return t == r
      if not t:
         return s == r
      if s[0] == r[0]:
         if self.solve(s[1:], t, r[1:]):
            return True
         if t[0] == r[0]:
            if self.solve(s, t[1:], r[1:]):
               return True
         return False
ob = Solution()
s = "xyz"
t = "mno"
r = "xymnoz"
print(ob.solve(s, t, r))


"xyz", "mno", "xymnoz"


Published on 26-Dec-2020 10:37:38