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

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



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
Updated on: 2020-10-06T06:25:37+05:30

611 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements