Skip to content

Instantly share code, notes, and snippets.

@vinayverghese
Forked from primaryobjects/1-isomorphic.js
Last active August 20, 2018 20:34
Show Gist options
  • Select an option

  • Save vinayverghese/dc6c06c053fa693f81b2da2b8dfaf15f to your computer and use it in GitHub Desktop.

Select an option

Save vinayverghese/dc6c06c053fa693f81b2da2b8dfaf15f 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;
};
/*
https://js-algorithms.tutorialhorizon.com/2015/10/21/determine-if-given-strings-are-isomorphic/
*/
function isomorphic (str1, str2) {
var len1 = str1.length;
if (len1 != str2.length) {
console.log('Both strings have different lenghts');
return false;
}
var chMap = {};
for (var i = 0; i < len1; i++) {
if (!chMap[str1[i]]) {
chMap[str1[i]] = str2[i];
} else if (chMap[str1[i]] !== str2[i]) {
console.log('Both strings differ in maaping at index ' + i);
return false;
}
}
return true;
}
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