87 Scramble String

判断两个字符串是否是scramble string,即将字符串通过二叉树分解,交换其中的非叶子节点的子节点得到。

递归➕剪枝
s1分为s11和s12,s2分为s21和s22,判断 isScramble(s11,s21) && isScramble(s12,s22) 或 isScramble(s12,s21) && isScramble(s11,s22)

递归之前进行剪枝,判断两个起始判断的部分字母是否相同,用Unicode编码进行判断,O(n) 复杂度,faster than 100%

/**
 * @param {string} s1
 * @param {string} s2
 * @return {boolean}
 */
var isScramble = function(s1, s2) {
    if(s1.length != s2.length) return false
    if(s1 === s2) return true
    var l = 0
    var r = 0
    for (var i = 0, j = s1.length - 1; i < s1.length; i++, j--){
        l ^= s1.charCodeAt(i) ^ s2.charCodeAt(i)
        r ^= s1.charCodeAt(i) ^ s2.charCodeAt(j)
        if (l === 0 && i < s1.length - 1){
            if (isScramble(s1.substring(0, i + 1), s2.substring(0, i + 1)) && 
              isScramble(s1.substring(i + 1), s2.substring(i + 1)))
            return true
        }
        if (r === 0 && i < s1.length - 1){
            if (isScramble(s1.substring(0, i + 1), s2.substring(s1.length - i - 1)) && 
              isScramble(s1.substring(i + 1), s2.substring(0, s1.length - i - 1)))
            return true
        }
    }
    return false
};

你可能感兴趣的:(87 Scramble String)