Check if it is possible to transform one string to another in Python


Suppose we have two strings s and t, t is in uppercase. We have to check whether we can convert s to t by performing following operations.

  • Convert some lowercase letters uppercase.
  • Remove all of the lowercase letters.

So, if the input is like s = "fanToM", t = "TOM", then the output will be True as we can change ‘o’ to ‘O’ then remove all other lowercase letters from s to make it t.

To solve this, we will follow these steps −

  • n := size of s, m := size of t
  • dp:= a matrix of size (m + 1)x(n + 1) and fill with False
  • dp[0, 0] := True
  • for i in range 0 to size of s - 1, do
    • for j in range 0 to size of t, do
      • if dp[i, j] is True, then
        • if j < size of t and s[i] in uppercase is same as t[j], then
          • dp[i + 1, j + 1] := True
        • if s[i] is not in uppercase, then
          • dp[i + 1, j] := True
  • return dp[n, m]

Example

Let us see the following implementation to get better understanding −

 Live Demo

def solve(s,t):
   n = len(s)
   m = len(t)
   dp= [[False for i in range(m+1)] for i in range(n+1)]
   dp[0][0] = True
   for i in range(len(s)):
      for j in range(len(t)+1):
         if dp[i][j] == True:
            if j < len(t) and (s[i].upper() == t[j]):
               dp[i + 1][j + 1] = True
            if s[i].isupper()==False:
               dp[i + 1][j] = True
   return dp[n][m]
s = "fanToM"
t = "TOM"
print(solve(s, t))

Input

"fanToM", "TOM"

Output

True

Updated on: 19-Jan-2021

329 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements