

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 determine if two strings are close in Python
Suppose we have two strings, s and t, we have to check whether s and t are close or not. We can say two strings are close if we can attain one from the other using the following operations −
Exchange any two existing characters. (like abcde to aecdb)
Change every occurrence of one existing character into another existing character, and do the same with the other characters also. (like aacabb -> bbcbaa (here all a's are converted to b's, and vice versa))
We can use the operations on either string as many times as we want.
So, if the input is like s = "zxyyyx", t = "xyyzzz", then the output will be true, because we can get t from s in 3 operations. ("zxyyyx" -> "zxxyyy"), ("zxxyyy" -> "yxxzzz"), and ("yxxzzz" -> "xyyzzz").
To solve this, we will follow these steps −
if s and t have any uncommon character, then
return False
a := list of all frequency values of characters in s
b := list of all frequency values of characters in t
sort the list a
sort the list b
if a is not same as b, then
return False
return True
Example
Let us see the following implementation to get better understanding −
from collections import Counter def solve(s, t): if set(s) != set(t): return False a = list(Counter(s).values()) b = list(Counter(t).values()) a.sort() b.sort() if a != b: return False return True s = "zxyyyx" t = "xyyzzz" print(solve(s, t))
Input
"zxyyyx", "xyyzzz"
Output
True
- Related Questions & Answers
- Python Pandas - Determine if two Index objects are equal
- Java Program to Check if two strings are anagram
- Python - Check if two strings are isomorphic in nature
- C# program to determine if Two Words Are Anagrams of Each Other
- C Program to check if two strings are same or not
- Write Code to Determine if Two Trees are Identical in C++
- Python program to remove words that are common in two Strings
- How to check if two strings are equal in Java?
- Python Pandas - Determine if two Index objects with opposite orders are equal or not
- Python Program to check if two given matrices are identical
- Python Program to Check If Two Numbers are Amicable Numbers
- Check if two strings are equal or not in Arduino
- C# program to determine if any two integers in array sum to given integer
- Python Pandas - Determine if two CategoricalIndex objects contain the same elements
- Check if two strings are equal while ignoring case in Arduino