Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active May 24, 2019 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save primaryobjects/933e1141c0b3dad27a96faa2abb4dae3 to your computer and use it in GitHub Desktop.
Save primaryobjects/933e1141c0b3dad27a96faa2abb4dae3 to your computer and use it in GitHub Desktop.
Isomorphic Strings
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isIsomorphic = function(s, t) {
var result = true;
if (s.length === t.length) {
var hash1 = [];
var hash2 = [];
for (var i=0; i<s.length; i++) {
var char1 = s[i];
var char2 = t[i];
// If the character's last seen position doesn't match up, then not isomorphic.
if (hash1[char1] !== hash2[char2]) {
result = false;
break;
}
else {
// Store the last seen position of this character.
hash1[char1] = i;
hash2[char2] = i;
}
}
}
else {
result = false;
}
return result;
};
//
// This works, but is slower.
//
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isIsomorphic = function(s, t) {
var result = false;
if (s.length === t.length) {
for (var i=0; i<s.length; i++) {
var char1 = s[i];
var char2 = t[i];
var re1 = new RegExp(char1, "g");
var re2 = new RegExp(char2, "g");
s = s.replace(re1, i);
t = t.replace(re2, i);
}
result = s === t;
}
return result;
};
Given two strings s and t, determine if they are isomorphic.
Two strings 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.
For example,
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.
Note:
You may assume both s and t have the same length.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment