/**
* Checks if two strings are isomorphic.
* Two strings s and t are isomorphic if the characters in s can be replaced to get t.
* All occurrences of a character must be replaced with another character while preserving the order of characters.
* No two characters may map to the same character, but a character may map to itself.
*
* @param {string} s The first string.
* @param {string} t The second string.
* @return {boolean} True if the strings are isomorphic, false otherwise.
*/
function isIsomorphic(s, t) {
if (s.length !== t.length) {
return false;
}
const sMap = new Map();
const tMap = new Map();
for (let i = 0; i < s.length; i++) {
const sChar = s[i];
const tChar = t[i];
if (!sMap.has(sChar)) {
sMap.set(sChar, tChar);
} else if (sMap.get(sChar) !== tChar) {
return false;
}
if (!tMap.has(tChar)) {
tMap.set(tChar, sChar);
} else if (tMap.get(tChar) !== sChar) {
return false;
}
}
return true;
}
// Example usage:
console.log(isIsomorphic("egg", "add")); // true
console.log(isIsomorphic("foo", "bar")); // false
console.log(isIsomorphic("paper", "title")); // true
console.log(isIsomorphic("badc", "baba")); // false 'a' maps to both 'a' and 'b' in t
console.log(isIsomorphic("", "")); // true - Empty strings are considered isomorphic
console.log(isIsomorphic("ab", "ca")); //true
Explanation and Improvements:
-
Handles Empty Strings: The code now correctly handles empty strings as isomorphic.
-
Two Maps for Bijective Mapping: The crucial improvement is the use of two maps:
sMap
andtMap
. This ensures a one-to-one (bijective) mapping between characters. The original approach with a single map could lead to incorrect results (e.g., "badc" and "baba" would have been considered isomorphic with a single map). -
Clearer Variable Names:
sChar
andtChar
improve readability. -
JSDoc Comments: Added JSDoc style comments to clearly explain the function's purpose and parameters.
How it works (with the two maps):
sMap
: Stores mappings from characters ins
to characters int
.tMap
: Stores mappings from characters int
to characters ins
.
For each character pair:
-
It checks if the character from
s
already exists as a key insMap
.- If it doesn't, it adds the mapping (sChar -> tChar).
- If it does, it verifies that the existing mapped value matches the current
tChar
. If not, the strings are not isomorphic.
-
It performs the same check using
tMap
(tChar -> sChar).
This two-way check ensures that no two characters in s
map to the same character in t
and vice-versa, enforcing the isomorphism condition.
This improved version is more robust and accurately determines string isomorphism. It addresses the potential flaw in the single-map approach.