leetcode 087 —— Scramble String

来源:互联网 发布:java ocr文字识别 编辑:程序博客网 时间:2024/05/22 12:01

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.


思路1:递归法,检测左右两个子串是否符合要求(那个if语句有点丑。。。)运行时间16ms,但是还可以提速,用动态规划

class Solution {public:bool isScramble(string s1, string s2) {if (!isValid(s1,s2)) return false;  //长度不等,字符数不等,直接returnint n = s1.size();if (n == 1) return s1[0] == s2[0];for (int i = 1; i < n; i++){if ((isScramble(s1.substr(0, i), s2.substr(0, i)) &&     isScramble(s1.substr(i, n - i), s2.substr(i, n - i)))     ||    (isScramble(s1.substr(0, i), s2.substr(n-i, i)) &&     isScramble(s1.substr(i, n - i), s2.substr(0, n - i))))return true;}return false;}bool isValid(string &s1, string &s2){if (s1.size() != s2.size()) return false;int *a = new int[128];int *b = new int[128];for (int i = 0; i < s1.size(); i++){a[s1[i]]++;b[s2[i]]++;}for (int i = 0; i < 128; i++){if (a[i] != b[i])return false;}return true;delete a, b;}};


思路2 :动态规划法,程序如下,但是时间居然是176ms,是不是可以认为动态规划未必能有效降低复杂度。好的递归还是很厉害的。有时间要研究一下剪枝

class Solution {public:bool isScramble(string s1, string s2) {if (s1.size() != s2.size()) return false;int n = s1.size();if (n == 1) return s1[0] == s2[0];vector<vector<vector<bool>>> res(n, vector<vector<bool>>(n, vector<bool>(n + 1, false)));for (int i = 0; i < n; i++){for (int j = 0; j < n;j++)res[0][i][j] = (s1[i] == s2[j]);}for (int len = 1; len <= n; len++){    //当前进行匹配的字符串长度for (int i = 0; i <= n-len; i++){for (int j = 0; j <= n-len; j++){for (int m = 1; m < len; m++){if (res[m - 1][i][j] && res[len - m - 1][i + m][j + m])res[len -1 ][i][j] = true;else if (res[m - 1][i][j + len - m] && res[len - m - 1][i + m][j])res[len - 1][i][j] = true;}}}}return res[n - 1][0][0];}}a;


0 0
原创粉丝点击