Leetcode NO.87 Scramble String

来源:互联网 发布:java基础入门培训学校 编辑:程序博客网 时间:2024/04/30 04:10

本题题目要求如下:

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.

本题提示给的是动态规划,是一道hard题。。。想DP的optimal substructure确实想了一会儿没有想出来,于是就准备用recursive的方法解决了,如果用recursive,感觉这道题充其量是一道中档题。。。因为算法分析学的不好,哪位可以告诉一下本题用DP相对于recursive的优势在哪里?(除了recursive如果层数太多可能导致stack overflow)

基本思路很简单,

举个栗子"abcde"和"hijkl"

有四大种可能性,该字符串是scramble的,每种可能性下面有两小种可能性

(1.1)("a" "h“ are scramble) and ("bcde" "ijkl" are scramble)

(1.2)("a" "l" are scramble) and ("bcde" "hijk" are scramble)


(2.1)("ab" "hi" are scramble) and ("cde" "jkl" are scramble)

(2.2)("ab" "kl" are scramble) and ("cde" "hij" are scramble)


(3.1)("abc" "hij" are scramble) and ("de" and "kl" are scramble)

(3.2)


(4.1)

(4.2)

由于语言表达有点烂,所以就举了栗子。。。后面几种也很好推。。

代码如下:

class Solution {public:    bool isScramble(string s1, string s2) {    if (s1 == s2) {return true;    }    /* if have different characters, return false */    string tmp_s1 = s1;    string tmp_s2 = s2;    int sz = s1.length();    sort(tmp_s1.begin(), tmp_s1.end());    sort(tmp_s2.begin(), tmp_s2.end());    if (tmp_s1 != tmp_s2) {    return false;    }    for (int i = 1; i < sz; ++i) {        if (isScramble(s1.substr(0, i), s2.substr(0, i)) and isScramble(s1.substr(i), s2.substr(i))) {        return true;        }        if (isScramble(s1.substr(0, i), s2.substr(sz-i)) and isScramble(s1.substr(i), s2.substr(0, sz-i))) {        return true;        }        }        return false;    }};


0 0
原创粉丝点击