Given a stringS1, We may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
Below is one possible representationS1="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 T
We say that"Rgeat"
Is a scrambled string"Great"
.
Similarly, if we continue to swap the children of nodes"Eat"
And""
, It produces a scrambled string"Rgtae"
.
Rgtae/rg Tae/\/r g ta E/T
We say that"Rgtae"
Is a scrambled string"Great"
.
Given two stringsS1AndS2Of the same length, determine ifS2Is a scrambled stringS1.
Example 1:
Input: S1 = "great", S2 = "rgeat" output: True
Example 2:
Input: S1 = "ABCDE", S2 = "caebd" output: false
AC code:
Class solution {public: bool isscramble (string S1, string S2) {If (S1 = S2) return true; int Len = s1.length (); vector <int> V (26, 0); For (INT I = 0; I <Len; ++ I) {v [S1 [I]-'a'] ++; V [S2 [I]-'a'] --;} For (INT I = 0; I <26; ++ I) {If (V [I]! = 0) return false;} For (INT I = 1; I <Len; ++ I) {If (isscramble (s1.substr (0, I), s2.substr (0, i) & isscramble (s1.substr (I), s2.substr (I) return true; If (isscramble (s1.substr (0, I), s2.substr (LEN-I )) & isscramble (s1.substr (I), s2.substr (0, len-I) return true ;}return false ;}};
Runtime:0 MS, faster100.00% of C ++ online submissions for scramble string.
87. Scramble string