leetcode Scramble String

递归调用子问题。每次分成子问题处理,注意子问题不能为空。

class Solution {

public:
    bool isScramble(string s1, string s2) {
        const int n1 = s1.size();
        const int n2 = s2.size();
        if(n1!=n2)return false;
        if(n1==0)return true;
        return solve(s1,s2);
    }
private:
    bool solve(const string &s1,const string &s2){
        
        const int n = s1.size();
        if(n==1){
            return s1[0]==s2[0];
        }
        int count[128];
        memset(count,0,sizeof(count));
        for(int i = 0;i<n;i++)count[s1[i]]++;
        for(int i = 0;i<n;i++)if(count[s2[i]]==0){
            return false;
        }else count[s2[i]]--;
        string tmp1,tmp2;
        string tmp3,tmp4;
        string tmp5,tmp6;
        for(int i = n-1;i>=0;i--){
            tmp2.push_back(s1[i]);
            tmp4.push_back(s2[i]);
            tmp6.push_back(s2[n-i-1]);
        }
        for(int i = 1;i<=n-1;i++){
            tmp1.push_back(s1[i-1]);
            tmp2.pop_back();
            tmp3.push_back(s2[i-1]);
            tmp4.pop_back();
            bool ok = solve(tmp1,tmp3) &solve(tmp2,tmp4);
            if(ok)return true;
            tmp5.push_back(s2[n-i]);
            tmp6.pop_back();
            ok = solve(tmp1,tmp5) &solve(tmp2,tmp6);
            if(ok)return true;
        }
        return false;
        
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值