- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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 Articles
- Java Program to Check if two strings are anagram
- Golang Program to Check if two Strings are Anagram
- Python - Check if two strings are isomorphic in nature
- Python program to remove words that are common in two Strings
- Python Pandas - Determine if two Index objects are equal
- C Program to check if two strings are same or not
- C# program to determine if Two Words Are Anagrams of Each Other
- Program to merge two strings in alternating fashion in Python
- How to check if two strings are equal in Java?
- Program to add two numbers represented as strings in Python
- Program to find largest merge of two strings in Python
- Program to perform prefix compression from two strings in Python
- Write Code to Determine if Two Trees are Identical in C++
- Python program to find uncommon words from two Strings
- Program to split two strings to make palindrome using Python
