*leetcode #87 in cpp

Solution:

Since the scramble is made by constructing a binary tree and swapping them randomly, we could consider what property is in this construction. 

Property 1 : Suppose l is the left tree and r is the right tree, l would be either at left of r or at right of r in the scramble. 

Say 'great' and the partition point is  'r', then l = 'gr' and r = 'eat'. 

the scramble could be 'eatgr' or 'great', where l is at the right or left of r. 

But l would never be mixed among r. Say 'egart' is not the scramble given the partition point is 'r'. 

Property 2: if A(left tree is al, right tree is ar) is a scramble of B(left tree is bl, right tree is br), then either 1. al is scramble of bl and ar is the scramble of br or 2. al is the scramble of br and ar of bl.  

This property is a result of property 1. 


Thus to see if a string is a scramble of another string, we try to find a partition point and see if the left tree and right tree are scramble of the ones of another string. Note that this is a recurrent structure. 

Code:

class Solution {
public:
    bool isScramble(string s1, string s2) {
        int sublen; 
        int len = s1.length();
        if(len == 1) return s1[0] == s2[0];
        if(len == 2){
            return (s1[1] == s2[0] && s1[0] == s2[1]) || (s1[1]== s2[1] && s1[0] == s2[0]);
        }
        string temp1 = s1;
        string temp2 = s2; 
        sort(temp1.begin(), temp1.end());
        sort(temp2.begin(), temp2.end());
        if(temp1!=temp2) return false;
        //two cases string 1 is scramble of s2. 
        //1. s1's left is scramble of s2's right and s1's right is scramble of s2's left
        //2. s1's left is scramble of s2's left and s1's right is scramble of s2's right
        for(sublen = 1; sublen < len; sublen++){//make partition point
            //compare [aaa bbbb] to [aaa bbbb]
            if(isScramble(s1.substr(0,sublen), s2.substr(0,sublen)) && isScramble(s1.substr(sublen, len-sublen), s2.substr(sublen, len-sublen))) return true;
            //copare [aaa bbbb] to [bbbb aaa]
            if(isScramble(s1.substr(0, sublen), s2.substr(len-sublen, sublen)) && isScramble(s1.substr(sublen, len - sublen), s2.substr(0,len - sublen)))
                return true;
            
            
        }
        
        return false;
    }
   
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值