-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
61 lines (54 loc) · 1.33 KB
/
main.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
// URL: https://leetcode.com/problems/scramble-string/
const _isScramble = function (s1, s2, trackMap) {
if (s1.length !== s2.length) return false;
if (s1 === s2) return true;
if (s1.length === 0 || s2.length === 0) return true;
const trackKey = s1 + s2;
if (trackKey in trackMap) return !!trackMap[trackKey];
let result = false;
let xorFW = 0;
let xorBW = 0;
for (
var i = 0, j = s1.length - 1, iPlus = 1;
i < s1.length - 1;
i++, j--, iPlus++
) {
xorFW ^= s1.charCodeAt(i) ^ s2.charCodeAt(i);
xorBW ^= s1.charCodeAt(i) ^ s2.charCodeAt(j);
if (
xorFW === 0 &&
_isScramble(s1.substring(0, iPlus), s2.substring(0, iPlus), trackMap) &&
_isScramble(s1.substring(iPlus), s2.substring(iPlus), trackMap)
) {
result = true;
break;
}
if (
xorBW === 0 &&
_isScramble(
s1.substring(0, iPlus),
s2.substring(s1.length - iPlus),
trackMap
) &&
_isScramble(
s1.substring(iPlus),
s2.substring(0, s1.length - iPlus),
trackMap
)
) {
result = true;
break;
}
}
trackMap[trackKey] = result;
trackMap[s2 + s1] = result;
return result;
};
/**
* @param {string} s1
* @param {string} s2
* @return {boolean}
*/
const isScramble = function (s1, s2) {
return _isScramble(s1, s2, {});
};