【LeetCode】87. Scramble String

来源:互联网 发布:淘宝原单是真的吗 编辑:程序博客网 时间:2024/05/01 12:02

【LeetCode】87. 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.


【输入输出】

  "abcd", "bdac"                                                                                                   -> false
  "abcdefghijklmnopq", "efghijklmnopqcadb"                                                       -> false
  "oatzzffqpnwcxhejzjsnpmkmzngneo", "acegneonzmkmpnsjzjhxwnpqffzzto"    -> true
  "oad", "ado"                                                                                                       -> true
  "great", "rgtae"                                                                                                   -> true


【解题思路】

DFS+递归1. 若s1前n项所包含的字符与s2前n项相同,递归判断s1前n项和s2前n项,s1剩下项和s2剩下项是否均为scrambled string.2. 若s1前n项所包含的字符与s2后n项相同,递归判断s1前n项和s2后n项,s1剩下项和s2剩下项是否均为scrambled string.


【代码】

class Solution {public:bool isScramble(string s1, string s2) {if (s1 == s2) return true;if (s1.length() != s2.length() || (s1.length() == 1 && s2.length() == 1)) return false;bool ans = false;for (int i = 0; i < s1.length(); i++) {string temp1 = toSortString(s1.substr(0, i + 1));string temp2 = toSortString(s2.substr(0, i + 1));string temp3 = toSortString(s1.substr(s1.length() - i - 1, i + 1));if (temp1 == temp2 && i != s1.length() - 1) ans = isScramble(s1.substr(0, i + 1), s2.substr(0, i + 1)) && isScramble(s1.substr(i + 1, s1.length() - i - 1), s2.substr(i + 1, s1.length() - i - 1));if (temp3 == temp2 && i != s1.length() - 1) ans = isScramble(s1.substr(0, s1.length() - i - 1), s2.substr(i + 1, s1.length() - i - 1)) && isScramble(s1.substr(s1.length() - i - 1, i + 1), s2.substr(0, i + 1));if (ans) return ans;}return false;}string toSortString(string s) {string ans = s;sort(&ans[0], &ans[0] + s.length());return ans;}};
0 0