Skip to content

Commit 3cd9f7e

Browse files
committed
Create isomorphic-strings.js
1 parent cd28277 commit 3cd9f7e

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

leetcode/isomorphic-strings.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
* Question: 同构同形字符串
3+
4+
* Given two strings s and t, determine if they are isomorphic.
5+
6+
* Two strings are isomorphic if the characters in s can be replaced to get t.
7+
8+
* 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.
9+
10+
*For example,
11+
*Given "egg", "add", return true.
12+
13+
*Given "foo", "bar", return false.
14+
15+
*Given "paper", "title", return true.
16+
17+
*Note:
18+
* You may assume both s and t have the same length.
19+
*/
20+
21+
22+
/**
23+
* @param {string} s
24+
* @param {string} t
25+
* @return {boolean}
26+
*/
27+
var isIsomorphic = function(s, t) {
28+
29+
var i = s.length - 1;
30+
var sMap = {};
31+
var tMap = {};
32+
33+
for (; 0 <= i; i--) {
34+
var source = sMap[t[i]];
35+
var target = tMap[s[i]];
36+
if (!source && !target){
37+
sMap[t[i]] = s[i];
38+
tMap[s[i]] = t[i];
39+
} else if(source !== s[i] || target !== t[i]) {
40+
return false;
41+
}
42+
43+
}
44+
45+
return true;
46+
}

0 commit comments

Comments
 (0)