|
| 1 | +/** |
| 2 | + * A simply solution but not efficient consider every character of ‘str1′ and |
| 3 | + * check if all occurrences of it map to same character occurrences in ‘str2′. |
| 4 | + * Time complexity of this solution is O(n*n). |
| 5 | + * |
| 6 | + * This is a better solution (NOT ACCEPTED, Time limit exceeded). |
| 7 | + * 1. check if t[i] is in the map. If yes, find out the key associated with t[i] |
| 8 | + * if key exists, but s[i] is not equal to key, return false; |
| 9 | + * if key is null, but s[i] exists in the map and map[s[i]] is not equal to t[i] |
| 10 | + * return false. |
| 11 | + * |
| 12 | + *@param {string} s |
| 13 | + *@param {string} t |
| 14 | + *@return {boolean} |
| 15 | + */ |
| 16 | +varisIsomorphic=function(s,t){ |
| 17 | +varmap={}; |
| 18 | +for(vari=0;i<s.length;i++){ |
| 19 | +varkey=map.getKeyByValue(t[i]); |
| 20 | +if(key&&s[i]!==key){ |
| 21 | +returnfalse; |
| 22 | +}elseif(s[i]inmap){ |
| 23 | +if(map[s[i]]!==t[i]){ |
| 24 | +returnfalse; |
| 25 | +} |
| 26 | +}else{ |
| 27 | +map[s[i]]=t[i]; |
| 28 | +} |
| 29 | +} |
| 30 | +returntrue; |
| 31 | +}; |
| 32 | + |
| 33 | +Object.prototype.getKeyByValue=function(value){ |
| 34 | +for(varpropinthis){ |
| 35 | +if(this.hasOwnProperty(prop)){ |
| 36 | +if(this[prop]===value) |
| 37 | +returnprop; |
| 38 | +} |
| 39 | +} |
| 40 | +}; |