
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Buddy Strings in Python
Suppose we have two strings A and B of lowercase letters; we have to check whether we can swap two letters in A so that the result equals to B or not.
So, if the input is like A = "ba", B = "ab", then the output will be True.
To solve this, we will follow these steps −
- if size of A is not same as size of B, then
- return False
- otherwise when A and B has any element that are not common, then
- return False
- otherwise when A is same as B and all characters are distinct in A, then
- return False
- otherwise,
- count:= 0
- for i in range 0 to size of A, do
- if A[i] is not same as B[i], then
- count := count + 1
- if count is same as 3, then
- return False
- if A[i] is not same as B[i], then
- return True
Let us see the following implementation to get better understanding −
Example
class Solution: def buddyStrings(self, A, B): if len(A)!=len(B): return False elif sorted(A)!=sorted(B): return False elif A==B and len(set(A))==len(A): return False else: count=0 for i in range(len(A)): if A[i]!=B[i]: count+=1 if count==3: return False return True ob = Solution() print(ob.buddyStrings("ba","ab"))
Input
"ba","ab"
Output
True
Advertisements