Scramble String

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章