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
| var isScramble = function (s1, s2) { const cache = {} const check = (s1, s2) => { if (s1.length !== s2.length) { return false } if (s1 === s2) { return true } if (s1.split('').sort().join('') !== s2.split('').sort().join('')) { return false } for (let i = 1; i < s2.length; ++i) { const [part11, part12] = [s1.substring(0, i), s1.substring(i)] const [part21, part22] = [s2.substring(0, i), s2.substring(i)] const [key1121, key1222] = [`${part11},${part21}`, `${part12},${part22}`] cache[key1121] = cache[key1121] !== undefined ? cache[key1121] : check(part11, part21) cache[key1222] = cache[key1222] !== undefined ? cache[key1222] : check(part12, part22) if (cache[key1121] && cache[key1222]) { return true } const [part23, part24] = [s2.substring(s2.length - i), s2.substring(0, s2.length - i)] const [key1123, key1224] = [`${part11},${part23}`, `${part12},${part24}`] cache[key1123] = cache[key1123] !== undefined ? cache[key1123] : check(part11, part23) cache[key1224] = cache[key1224] !== undefined ? cache[key1224] : check(part12, part24) if (cache[key1123] && cache[key1224]) { return true } } return false } return check(s1, s2) }
|