String Transforms Into Another String in Python

PythonServer Side ProgrammingProgramming

Suppose we have two strings str1 and str2. And their lengths are same, we have to check whether we can transform str1 into str2 by doing zero or more conversions.

In one conversion we can convert all occurrences of one character in str1 to any other lowercase English character. We have to check whether we can transform str1 into str2 or not.

So, if the input is like str1 = "aabcc", str2 = "ccdee", then the output will be true, as Convert 'c' to 'e' then 'b' to 'd' then 'a' to 'c'. Here we have to keep in mind that the order of conversions matter.

To solve this, we will follow these steps −

  • Define a function compress(). This will take s

  • n := size of s

  • a := a new list

  • count := 1

  • for i in range 1 to n, do

    • if s[i] is not same as s[i-1], then

      • insert count at the end of a

      • count:= 1

    • otherwise,

      • count := count + 1

  • insert count at the end of a

  • return a

  • Define a function canConvert(). This will take str1, str2

  • a := compress(str1)

  • b := compress(str2)

  • n := size of a, m := size of b

  • d:= a new map

  • n := minimum of n, m

  • i := 0

  • while i<n is non-zero, do

    • if a[i] >b[i] is non-zero, then

      • return False

    • i := i + 1

  • for each i in str2, do

    • if i not in d is non-zero, then

      • d[i]:= 1

  • return True if 26 - size of d is non zero or str1 is same as str2 otherwise False

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):
   def compress(self,s):
      n = len(s)
      a = []
      count = 1
      for i in range(1,n):
         if s[i]!=s[i-1]:
            a.append(count)
            count=1
         else:
            count+=1
      a.append(count)
      return a
   def canConvert(self, str1, str2):
      a = self.compress(str1)
      b = self.compress(str2)
      n = len(a)
      m = len(b)
      d={}
      n = min(n,m)
      i = 0
      while i<n:
         if a[i]>b[i]:
            return False
            i+=1
         for i in str2:
            if i not in d:
               d[i]=1
      return True if 26-len(d) or str1 == str2 else False

ob = Solution()
print(ob.canConvert("aabcc", "ccdee"))

Input

"aabcc", "ccdee"

Output

True
raja
Published on 11-Jul-2020 12:26:30
Advertisements