The Isomorphic Strings solutions are below.
15 Jun 2024•Easy•C++ / Python / TypeScript
Isomorphic Strings
C++, Python and TypeScript solutions for Isomorphic Strings.
Solution files
Python•isomorphic-strings/synced-solution.py
def isIsomorphic(s: str, t: str) -> bool:
if len(s) != len(t):
return False
s_to_t = {}
t_to_s = {}
for char_s, char_t in zip(s, t):
if char_s in s_to_t:
if s_to_t[char_s] != char_t:
return False
else:
s_to_t[char_s] = char_t
if char_t in t_to_s:
if t_to_s[char_t] != char_s:
return False
else:
t_to_s[char_t] = char_s
return True
C++•isomorphic-strings/synced-solution.cpp
class Solution {
public:
bool isIsomorphic(string s, string t) {
if (s.length() != t.length()) return false;
unordered_map<char, char> sToT;
unordered_map<char, char> tToS;
for (int i = 0; i < s.length(); i++) {
char charS = s[i];
char charT = t[i];
if (sToT.count(charS)) {
if (sToT[charS] != charT) return false;
} else {
sToT[charS] = charT;
}
if (tToS.count(charT)) {
if (tToS[charT] != charS) return false;
} else {
tToS[charT] = charS;
}
}
return true;
}
};
TypeScript•isomorphic-strings/synced-solution.ts
function isIsomorphic(s: string, t: string): boolean {
if (s.length !== t.length) return false;
const sToT = new Map<string, string>();
const tToS = new Map<string, string>();
for (let i = 0; i < s.length; i++) {
const charS = s[i];
const charT = t[i];
if (sToT.has(charS)) {
if (sToT.get(charS) !== charT) return false;
} else {
sToT.set(charS, charT);
}
if (tToS.has(charT)) {
if (tToS.get(charT) !== charS) return false;
} else {
tToS.set(charT, charS);
}
}
return true;
}