
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- if st[i] is not same as st[i+1], then
- return True
Let us see the following implementation to get better understanding −
Example
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
- Related Articles
- Program to check two strings can be equal by swapping characters or not in Python
- C++ program to check we can make two strings equal by swapping from third string
- Order strings by length of characters IN mYsql?
- C++ Program to Swapping Pair of Characters
- Golang program to swapping pair of characters
- Program to find largest substring between two equal characters in Python
- Program to get maximum length merge of two given strings in Python
- Python Program to Group Strings by K length Using Suffix
- Python program to Sort a List of Strings by the Number of Unique Characters
- C++ program to get length of strings, perform concatenation and swap characters
- C++ program to find uncommon characters in two given strings
- Find uncommon characters of the two strings in C++ Program
- Maximum length of balanced string after swapping and removal of characters in C++
- Python code to print common characters of two Strings in alphabetical order
- Program to check whether two trees can be formed by swapping nodes or not in Python

Advertisements