判斷兩個字符串是否是scramble string上煤,即將字符串通過二叉樹分解郎哭,交換其中的非葉子節(jié)點的子節(jié)點得到。
遞歸?剪枝
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
};