*leetcode #87 in cpp

来源:互联网 发布:php 上传图片到七牛 编辑:程序博客网 时间:2024/05/18 00:20

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
原创粉丝点击