不会翻译这个标题。。但是题意是给一个string s1,这个string被表示成一个二叉树。在树的叶节点,每个字母会被分到二叉树的每一个最小的分支上自成一支。
Below is one possible representation of s1 =
"great"
:great / \ gr eat / \ / \ g r e at / \ a t
To scramble the string, we may choose any non-leaf node and swap its two children.
For example, if we choose the node
"gr"
and swap its two children, it produces a scrambled string"rgeat"
.rgeat / \ rg eat / \ / \ r g e at / \ a tWe say that
"rgeat"
is a scrambled string of"great"
.
如上例子,great和rgeat是互为scramble string的。这题给的tag是DP但是DP的实现是三维的,几乎不可能在面试过程中完美实现。这里我给出的是递归解法,比较直观。
时间O(n!) - 我其实不是很确定
空间O(n) - 因为递归用到栈空间
1 /** 2 * @param {string} s1 3 * @param {string} s2 4 * @return {boolean} 5 */ 6 var isScramble = function(s1, s2) { 7 if (s1 === s2) return true; 8 const letters = new Array(128).fill(0); 9 const a = 'a'.charCodeAt(0); 10 for (let i = 0; i < s1.length; i++) { 11 letters[s1.charCodeAt(i) - a]++; 12 letters[s2.charCodeAt(i) - a]--; 13 } 14 for (let i = 0; i < 128; i++) { 15 if (letters[i] !== 0) return false; 16 } 17 for (let i = 1; i < s1.length; i++) { 18 if (isScramble(s1.substring(0, i), s2.substring(0, i)) && isScramble(s1.substring(i), s2.substring(i))) 19 return true; 20 if ( 21 isScramble(s1.substring(0, i), s2.substring(s2.length - i)) && 22 isScramble(s1.substring(i), s2.substring(0, s2.length - i)) 23 ) 24 return true; 25 } 26 return false; 27 };