Was it helpful?

Question

Program to check whether one string can be 1-to-1 mapped into another string in Python

PythonServer Side ProgrammingProgramming

Suppose we have two lowercase strings s, and t we have to check whether we can create one 1-to-1 mapping for each letter in s to another letter (may be the same letter) such that s can be mapped to t. (The ordering of characters will not be changed).

So, if the input is like s = "papa", t = "lili", then the output will be True, as we can create this mapping: "p" to "l", "a" -> "i"

To solve this, we will follow these steps −

  • s_dict := a new map
  • t_dict := a new map
  • for i in range 0 to minimum of s size and t size, do
    • if s[i] is present in s_dict, then
      • if s_dict[s[i]] is not same as t[i], then
        • return False
    • otherwise when t[i] is present in t_dict, then
      • if t_dict[t[i]] is not same as s[i], then
        • return False
    • otherwise,
      • s_dict[s[i]] := t[i]
      • t_dict[t[i]] := s[i]
  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s, t):
      s_dict = {}
      t_dict = {}
      for i in range(min(len(s), len(t))):
         if s[i] in s_dict:
            if s_dict[s[i]] != t[i]:
               return False
            elif t[i] in t_dict:
               if t_dict[t[i]] != s[i]:
                  return False
               else:
                  s_dict[s[i]] = t[i]
                  t_dict[t[i]] = s[i]
      return True
ob = Solution()
print(ob.solve("papa", "lili"))

Input

"papa", "lili"

Output

True
raja
Published on 05-Oct-2020 10:45:52
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top