Scramble String

来源:互联网 发布:java messagequeue 编辑:程序博客网 时间:2024/06/08 04:22

一. 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.

Difficulty:Hard

TIME:36MIN

解法(深度优先搜索)

一开始看到这道题以为很难,其实仔细思考了一下,发现也并不是特别难。

既然是一个树形结构,那么当然很容易就想到了递归。这道题的关键在于翻转,可以翻转一次,当然也可以翻转两次。翻转两次后就和原字符串等价了。

比如对于字符串great,如果我拆分成gr和eat两个字符串,那么我可以翻转一次变为eatgr,也可以此翻转两次变成great,所以要分两种情况考虑。

bool isScramble(string s1, string s2) {    string t1 = s1;    string t2 = s2;    sort(t1.begin(), t1.end()); //如果字符串很长可以改为计数排序    sort(t2.begin(), t2.end());    if(t1 != t2)        return false;    int len = s1.size();    if(len <= 3) //长度小于等于3而且字符相同,必定可以通过翻转得到        return true;    for(int i = 1; i < len; i++) {        /*假设翻转一次*/        if(isScramble(s1.substr(0, i), s2.substr(len - i)) && isScramble(s1.substr(i), s2.substr(0, len - i)))            return true;        /*假设翻转两次*/        if(isScramble(s1.substr(0, i), s2.substr(0, i)) && isScramble(s1.substr(i), s2.substr(i)))            return true;    }    return false;}

代码的时间复杂度小于O(n!)

优化(带备忘的深度优先搜索)

其实仔细看一下代码,就可以发现我们重复计算了很多之前已经计算过的值。因此,我们可以采用带备忘的深度优先搜索来提升代码的运行效率。

具体做法是采用一个map来记录两个子串的求值结果。

bool isScramble(string s1, string s2) {    unordered_map<string, bool> m; //用来记录两个子串是否出现过    return isScramble(s1, s2, m);}bool isScramble(string s1, string s2, unordered_map<string, bool> &m) {    int len = s1.size();    bool result = false;    if(len == 0)        return true;    else if(len == 1)        return s1 == s2;    else if(m.find(s1 + s2) != m.end())        return m[s1 + s2];    result = s1 == s2;    for (int k = 1; k < len && !result; k++) {        result = result || isScramble(s1.substr(0, k), s2.substr(len - k), m) && isScramble(s1.substr(k), s2.substr(0, len - k), m);        result = result || isScramble(s1.substr(0, k), s2.substr(0, k), m) && isScramble(s1.substr(k), s2.substr(k), m);    }    m[s1 + s2] = result;    return m[s1 + s2];}

代码的时间复杂度约为O(n4)

0 0