
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 1-to-1 String Mapping in Python
Suppose we have two lowercase strings s, and t we have to check whether we can create one 1-to-1 mapping for each letter in s to another letter (may be the same letter) such that s can be mapped to t. (The ordering of characters will not be changed).
So, if the input is like s = "papa", t = "lili", then the output will be True, as we can create this mapping: "p" to "l", "a" -> "i"
To solve this, we will follow these steps −
- s_dict := a new map
- t_dict := a new map
- for i in range 0 to minimum of s size and t size, do
- if s[i] is present in s_dict, then
- if s_dict[s[i]] is not same as t[i], then
- return False
- if s_dict[s[i]] is not same as t[i], then
- otherwise when t[i] is present in t_dict, then
- if t_dict[t[i]] is not same as s[i], then
- return False
- if t_dict[t[i]] is not same as s[i], then
- otherwise,
- s_dict[s[i]] := t[i]
- t_dict[t[i]] := s[i]
- if s[i] is present in s_dict, then
- return True
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s, t): s_dict = {} t_dict = {} for i in range(min(len(s), len(t))): if s[i] in s_dict: if s_dict[s[i]] != t[i]: return False elif t[i] in t_dict: if t_dict[t[i]] != s[i]: return False else: s_dict[s[i]] = t[i] t_dict[t[i]] = s[i] return True ob = Solution() print(ob.solve("papa", "lili"))
Input
"papa", "lili"
Output
True
Advertisements