Given A string S1, we may represent it as a binary tree by partitioning it to the Non-empty substrings Recursivel Y.
Below is one possible representation of S1 = "great"
:
Great / gr eat/\ / g r E at / a t
To scramble the string, we are choose any non-leaf node and swap it to the children.
for example, if we choose the Node " GR "
and swap its-children, it produces a scrambled string < Code style= "Font-family:menlo,monaco,consolas, ' Courier New ', monospace; font-size:13px; PADDING:2PX 4px; Color:rgb (199,37,78); Background-color:rgb (249,242,244) ">" Rgeat ".
Rgeat / RG eat/\ / r G e at / a t
We say is "rgeat"
a scrambled string of "great"
.
similarly, if we continue to swap the children of Nodes " eat "
and " at "
, it produces a scrambled String " Rgtae "
.
Rgtae / RG tae/\ / r G ta e / t a
We say is "rgtae"
a scrambled string of "great"
.
Given strings S1 and S2 of the same length, determine if S2 is a scrambled string of S1 .
This problem can is solved with brute force.
Class solution: # @param s1, a string # @param s2, a string # @return A Boolean def isscramble (self, S1, s 2): N, m = Len (S1), Len (S2) if n!=m or sorted (S1)!=sorted (S2): return False if n < 4 or S1 = = S2: re Turn True for I in range (1, N): if (self.isscramble (S1[:i],s2[:i]) and Self.isscramble (s1[i:], S2[i:]) or (self . isscramble (S1[:i], S2[-i:]) and Self.isscramble (s1[i:], S2[:-i])): return True return False
Scramble String Leetcode Python