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.
Example 1:
Input: s = "egg", t = "add" Output: true
Example 2:
Input: s = "foo", t = "bar" Output: false
Example 3:
Input: s = "paper", t = "title" Output: true
Note:
You may assume both s and t have the same length.
Algorithm for the same in Javascript:-
Code written in Javascript below:-
[cc lang = "javascript" lines="-1" tab_size="4" width="100%"]
/**
if (strArr.length !== s.length) return false;
for (var i = 0; i < s.length; i++) {
if (typeof patternMap[s[i]] === 'undefined')
patternMap[s[i]] = [];
if (typeof strMap[strArr[i]] === 'undefined')
strMap[strArr[i]] = [];
patternMap[s[i]].push(i);
strMap[strArr[i]] .push(i);
}
if (Object.keys(patternMap).length !== Object.keys(strMap).length) return false;
for (var key in patternMap) {
patOccurance += patternMap[key].join('').length;
patOccuranceVal += patternMap[key].join('');
}
for (var skey in strMap) {
strOccurance += strMap[skey].join('').length;
strOccuranceVal += strMap[skey].join('');
}
// console.log(patOccurance, patOccuranceVal, strOccurance, strOccuranceVal);
if (patOccuranceVal.length !== patOccurance.length) {
return (patOccuranceVal === strOccuranceVal);
}
else
return (patOccurance === strOccurance) || (patOccuranceVal === strOccuranceVal);
};
[/cc]