Leetcode: Scramble string
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"at"
, It produces a scrambled string"rgtae"
.
rgtae / rg tae / \ / r g ta e / t a
We say that"rgtae"
Is a scrambled string"great"
.
Given two stringsS1AndS2Of the same length, determine ifS2Is a scrambled stringS1.
Address: https://oj.leetcode.com/problems/scramble-string/
Algorithm: If the string S1 [0 ~ I] and S2 [0 ~ I] and S1 [I + 1 ~ N] and S2 [I + 1 ~ N] all meet the scrambled condition, so S1 and S2 are also met; if the string S1 [0 ~ I] and S2 [n-I ~ N] and S1 [I + 1 ~ N] and S2 [0 ~ N-i-1] Meet scrambled conditions, then S1 and S2 also meet, where I = 1... n. Note: Before recursive calling, use the isreasonstring function to determine whether the scrambled condition may be satisfied, which can reduce the number of recursion times. Code:
1 class Solution { 2 public: 3 bool isScramble(string s1, string s2) { 4 if(s1 == s2){ 5 return true; 6 } 7 if(s1.size() == 1){ 8 return false; 9 }10 int len = s1.size();11 for(int i = 1; i < len; ++i){12 string s11 = s1.substr(0,i);13 string s21 = s2.substr(0,i);14 string s12 = s1.substr(i,len-i);15 string s22 = s2.substr(i,len-i);16 if(isReasonString(s11,s21) && isReasonString(s12,s22) && isScramble(s11,s21) && isScramble(s12,s22)){17 return true;18 }19 s21 = s2.substr(len-i,i);20 s22 = s2.substr(0,len-i);21 if(isReasonString(s11,s21) && isReasonString(s12,s22) && isScramble(s11,s21) && isScramble(s12,s22)){22 return true;23 }24 }25 return false;26 }27 bool isReasonString(string s1, string s2){28 sort(s1.begin(),s1.end());29 sort(s2.begin(),s2.end());30 return s1 == s2;31 }32 };
Leetcode: Scramble string