首页 > 代码库 > LeetCode: Scramble String

LeetCode: Scramble String

LeetCode: Scramble String

Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.

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   t

We say that "rgeat" is 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 that "rgtae" is a scrambled string of "great".

Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.

地址:https://oj.leetcode.com/problems/scramble-string/

算法:如果字串S1[0~i]和S2[0~i]以及S1[i+1~n]和S2[i+1~n]都满足scrambled条件,那么S1和S2也满足;如果字串S1[0~i]和S2[n-i~n]以及S1[i+1~n]和S2[0~n-i-1]满足scrambled条件,那么S1和S2也满足,其中i=1...n。注意,我们在递归调用之前,用函数isReasonString先判断一下是否有可能满足scrambled条件,这样可以减少递归的次数。代码:

 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