
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
Check If Characters of One String Can Be Swapped to Form Another in Python
Suppose we have two strings s and t, we have to check whether we can generate t by swapping the character of the s.
So, if the input is like s = "worldlloeh" t = "helloworld", then the output will be True as we can swap characters from "worldlloeh" to make "helloworld".
To solve this, we will follow these steps −
- s_len := size of s, t_len := size of t
- if s_len is not same as t_len, then
- return False
- freq := a map to store all characters and their frequencies in s
- for i in range 0 to t_len, do
- freq[t[i]] := freq[t[i]] - 1
- if freq[t[i]] < 0, then
- return False
- return True
Let us see the following implementation to get better understanding −
Example
from collections import defaultdict def solve(s, t): s_len = len(s) t_len = len(t) if (s_len != t_len): return False freq = defaultdict(int) for char in s : freq[char] += 1 for i in range(t_len) : freq[t[i]] -= 1 if freq[t[i]] < 0: return False return True s = "worldlloeh" t = "helloworld" print(solve(s, t))
Input
"worldlloeh", "helloworld"
Output
True
Advertisements