-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathisomorphic-strings.js
75 lines (65 loc) · 1.36 KB
/
isomorphic-strings.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isIsomorphic = function (s, t) {
var len1 = s.length, len2 = t.length;
if (len1 !== len2) {
return false;
}
var mapA = [];
for (var i = 0; i < len1; i++) {
if (s[i] in mapA) {
if (mapA[s[i]] !== t[i]) {
return false;
}
} else {
mapA[s[i]] = t[i];
}
}
var mapB = [];
for (var j = 0; j < len1; j++) {
if (t[j] in mapB) {
if (mapB[t[j]] !== s[j]) {
return false;
}
} else {
mapB[t[j]] = s[j];
}
}
return true;
};
// Concise solution
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isIsomorphic = function (s, t) {
var len1 = s.length, len2 = t.length;
// check the length
if (len1 !== len2) {
return false;
}
// mapping from s to t
if (!isomorphic([], len1, s, t) || !isomorphic([], len2, t, s)) {
return false;
}
return true;
};
function isomorphic(hash, len, s, t) {
var i = 0;
while (i < len) {
if (hash[s[i]]) {
if (hash[s[i]] !== t[i]) {
return false;
}
} else {
hash[s[i]] = t[i];
}
i++;
}
return true;
}
// 时间 O(N) 空间 O(N)