Program to equal two strings of same length by swapping characters in Python

PythonServer Side ProgrammingProgramming

Suppose we have two strings s and t of length n. We can take one character from s and another from t and swap them. We can make unlimited number of swaps; we have to check whether it's possible to make the two strings equal or not.

So, if the input is like s = "xy", t = "yx", then the output will be True

To solve this, we will follow these steps −

  • st:= sort the string after concatenating s and t
  • for i in range 0 to size of st - 1, increase by 2, do
    • if st[i] is not same as st[i+1], then
      • return False
  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s, t):
      st=sorted(s+t)
      for i in range(0,len(st),2):
         if st[i]!=st[i+1]:
            return False
      return True
ob = Solution()
print(ob.solve("xy", "yx"))

Input

"xy", "yx"

Output

True
raja
Published on 06-Oct-2020 06:24:39
Advertisements