首页 > 代码库 > [leetcode]Scramble String

[leetcode]Scramble String

<style></style>

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.

这道题,题目都没读懂是什么意思~~,为自己的理解能力捉急~~,参考了http://blog.unieagle.net/2012/10/23/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Ascramble-string%EF%BC%8C%E4%B8%89%E7%BB%B4%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/和http://blog.theliuy.com/scramble-string/这两篇博客,看了代码才懂题的意思。用的就是动态规划。

c++代码:

#include <string>#include <iostream>#include <vector>using namespace std;class Solution {public:    int char_size;    bool isScramble(string s1, string s2) {		char_size = 26;        return isScrambleHelper(s1, s2);    }        bool isScrambleHelper(string &s1, string &s2) {        if (s1.size() != s2.size())            return false;        if (s1 == s2)            return true;                int size = s1.size();        vector<int> bucket(char_size, 0);        string s11, s12, s21, s22;                // Check wheter they have the same chars        for (int i = 0; i < s1.size(); ++i) {            bucket[s1[i] - ‘a‘] += 1;            bucket[s2[i] - ‘a‘] -= 1;        }        for (int i = 0; i < char_size; ++i) {            if (bucket[i] != 0)                return false;        }                for (int i = 1; i < size; ++i) {            s11 = s1.substr(0, i);            s12 = s1.substr(i);                        s21 = s2.substr(0, i);            s22 = s2.substr(i);            if (isScrambleHelper(s11, s21) && isScrambleHelper(s12, s22))                return true;                            s21 = s2.substr(size - i);            s22 = s2.substr(0, size - i);            if (isScrambleHelper(s11, s21) && isScrambleHelper(s12, s22))                return true;        }                return false;    }};int main(){	Solution s = Solution();	bool r = s.isScramble("great", "rgeat");	cout << r << endl;}

  

[leetcode]Scramble String