Problem Statement:
Given two strings s
and t
of the same length, determine whether it is possible to replace characters in s
such that it becomes identical to t
. Each character in s
can be replaced with at most one unique character from t
, and no two characters in s
can map to the same character in t
.
To solve this problem, we use two dictionaries (dic1
and dic2
) to map characters from s
to t
and t
to s
respectively. These mappings help ensure one-to-one correspondence between characters.
Initialize Variables:
dic1
and dic2
, to track mappings.flag
variable set to 1
, indicating success.Iterate Through Both Strings Simultaneously:
(s[i], t[i])
:
s[i]
is already in dic1
and maps to a different character than t[i]
, or if t[i]
is in dic2
and maps to a different character than s[i]
, set flag = 0
and break.s[i] -> t[i]
in dic1
and t[i] -> s[i]
in dic2
.Final Check:
flag
is still 1
after processing all characters, return True
.False
.def canTransform(s, t):
if len(s) != len(t):
return False
dic1 = {}
dic2 = {}
flag = 1
for i in range(len(s)):
if (s[i] in dic1 and dic1[s[i]] != t[i]) or (t[i] in dic2 and dic2[t[i]] != s[i]):
flag = 0
break
dic1[s[i]] = t[i]
dic2[t[i]] = s[i]
return flag == 1
---
**Input:**
`s = "abc", t = "def"`
**Execution:**
- `dic1`: `{'a': 'd', 'b': 'e', 'c': 'f'}`
- `dic2`: `{'d': 'a', 'e': 'b', 'f': 'c'}`
**Output:**
`True`
---
**Input:**
`s = "foo", t = "bar"`
**Execution:**
- Mapping `o -> a` is inconsistent.
**Output:**
`False`
---
**Input:**
`s = "add", t = "egg"`
**Execution:**
- `dic1`: `{'a': 'e', 'd': 'g'}`
- `dic2`: `{'e': 'a', 'g': 'd'}`
**Output:**
`True`
---
**Input:**
`s = "abc", t = "de"`
**Execution:**
- Since the lengths are different, no transformation is possible.
**Output:**
`False`
---
**Input:**
`s = "", t = ""`
**Execution:**
- Both strings are empty, so they are trivially the same.
**Output:**
`True`
https://leetcode.com/problems/isomorphic-strings
Loading component...
Loading component...
Main Function is not defined.
INPUT: s = "egg" , t = "add"
OUTPUT: true
public static bool isIsomorphic(string s , string t){
map<char , char>dict1;
map<char , char>dict2;
int i , flag = 1;
for(i = 0; i < s.length() && flag; i++){
if((dict1.count(s[i]) || dict2.count(t[i]) && (dict1[s[i] != t[i] && dict2[t[i] != s[i] )){
flag = 0;
}
else{
dict1[s[i]] = t[i];
dict2[t[i]] = s[i];
}
}
return flag;
}//function end
Utility Function is not required.