Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. (Hard)
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.
分析:
先考虑递归地解法, 对于字符串,枚举其分割位置i - 1,只有有一种分割位置满足
(isScramble(s1.substr(0, i),s2.substr(0, i)) && isScramble(s1.substr(i, s1.size() - i),s2.substr(i, s1.size() - i))
或者
(isScramble(s1.substr(0, i),s2.substr(s1.size() - i, i)) && isScramble(s1.substr(i, s1.size() - i), s2.substr(0,s1.size() - i)))
二者之一成立,则返回true,每个位置枚举后均不成立,则返回false
注:要有一些优化,否则超时过不了,比如s1 == s2 直接返回true, 将s1 s2排个序,之后不相等则直接返回false。
代码:
1 class Solution { 2 public: 3 bool isScramble(string s1, string s2) { 4 if (s1 == s2) { 5 return true; 6 } 7 if (s1.size() != s2.size()) { 8 return false; 9 } 10 if (s1.size() == 1 && s1[0] == s2[0]) { 11 return true; 12 } 13 string cmps1 = s1; 14 string cmps2 = s2; 15 sort(cmps1.begin(), cmps1.end()); 16 sort(cmps2.begin(), cmps2.end()); 17 if (cmps1 != cmps2) { 18 return false; 19 } 20 for (int i = 1; i < s1.size(); ++i) { 21 if ( (isScramble(s1.substr(0, i),s2.substr(0, i)) 22 && isScramble(s1.substr(i, s1.size() - i),s2.substr(i, s1.size() - i))) 23 || (isScramble(s1.substr(0, i),s2.substr(s1.size() - i, i)) 24 && isScramble(s1.substr(i, s1.size() - i), s2.substr(0,s1.size() - i))) ) { 25 return true; 26 } 27 } 28 return false; 29 } 30 };
好像还有三维动态规划的解法,回头再学习一个...