Check if it is possible to convert one string into another with given constraints in Python


Suppose we have two strings s and t with only three characters 'A', 'B' and '#'. We have to check whether it is possible to convert s into t by performing these operations on s.

  • 'A' can move only to the left hand side
  • 'B' can move only to the right hand side
  • Neither 'A' nor 'B' can cross each other

So, if the input is like s = "##AB##B" t = "A###B#B", then the output will be True as in s A can move easily to the left most position, and middle B can move one step to the right

To solve this, we will follow these steps −

  • s := a list by taking characters from s
  • t := a list by taking characters from t
  • if size of s is not same as size of t, then
    • return False
  • if count of 'A' in s and t are different or count of 'B' in s and t are different or, then
    • return False
  • for i in range 0 to size of s - 1, do
    • if s[i] is not same as '#', then
      • for j in range 0 to size of t - 1, do
        • if (t[j] is not same as s[i]) and t[j] is not same as '#', then
          • return False
        • if t[j] is same as s[i], then
          • t[j] := '#'
          • if s[i] is same as 'A' and i < j, then
            • return False
          • if s[i] is same as 'B' and i > j, then
            • return False
          • come out from loop
  • return True

Example

Let us see the following implementation to get better understanding −

 Live Demo

def solve(s, t):
   s = list(s)
   t = list(t)
   if len(s) != len(t):
      return False
   if s.count('A') != t.count('A') or s.count('B') != t.count('B'):
      return False
   for i in range(len(s)):
      if s[i] != '#':
         for j in range(len(t)):
            if (t[j] != s[i]) and t[j] != '#':
               return False
            if t[j] == s[i]:
               t[j] = '#'
               if s[i] == 'A' and i < j:
                  return False
               if s[i] == 'B' and i > j:
                  return False
               break
   return True
s = "##AB##B"
t = "A###B#B"
print (solve(s, t))

Input

"##AB##B", "A###B#B"

Output

True

Updated on: 18-Jan-2021

123 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements