- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to check two strings can be equal by swapping characters or not in Python
Suppose we have two lowercase strings s and t, they are of the same length. We can select one character from s and another from t and swap them. We can do this operation any number of times we want. Finally, we have to check whether it's possible to make the two strings same or not.
So, if the input is like s = "abcd" t = "cdab", then the output will be True
To solve this, we will follow these steps −
- fre := a list containing frequencies of each elements present in concatenated string of s and t
- for each cnt in list of all values of fre, do
- if cnt mod 2 is 1, then
- return False
- if cnt mod 2 is 1, then
- return True
Example
Let us see the following implementation to get better understanding −
from collections import Counter def solve(s, t): fre = Counter(s+t) for cnt in fre.values(): if cnt % 2: return False return True s = "abcd" t = "cdab" print(solve(s, t))
Input
"abcd", "cdab"
Output
True
Advertisements