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.
题意:给出两个字符串S1,S2,问S2是不是S1的scrambled string,因为规则有点烦,这里就不加描述
题解:首先知道,字符串是被划分成两个非空的子串的,并且作为树节点的左右儿子。并且可以随意交换左右儿子,以形成新的节点,scrambled string就是这样形成的。而我们知道,其实这样的串是很多的,但是归结起来,我们可以找到规律,首先如果只是一个字符,相等就为scrambled string,反之不是。那么我们就可以用DP的思路来解决。
以DP[i][j][k],表示S1的子串[i,i + k), S2的子串[j,j + k)是不是互为scrambled string,定下这个状态之后,我们来划分字符串,以p为界限划分成两个子串,有(1<=p<k),并且DP[i][j][k] = DP[i][j][p] && DP[i +p][j+p][k-p] || DP[i][j+k-p][p] && DP[i+p][j][k-p];状态转移方程就是这样了,用递归或者递推都可以做了。
class Solution { public: bool isScramble(string s1, string s2) { if (s1.length() != s2.length()) return false; strS1 = s1; strS2 = s2; return isScrambleOfSubstring(0, 0, s1.length()); } bool isScrambleOfSubstring(int x, int y, int len) { bool flag = false; if (len == 0) flag = true; else if (len == 1) flag = (strS1[x] == strS2[y]); else if (unSet.find(make_pair(strS1.substr(x, len), strS2.substr(y, len))) != unSet.end()) flag = unSet[make_pair(strS1.substr(x, len), strS2.substr(y, len))] == true; else { for (int i = 1; i < len; i++) { if (flag == true) break; flag = (isScrambleOfSubstring(x, y, i) && isScrambleOfSubstring(x + i, y + i, len - i)) || isScrambleOfSubstring(x, y + len - i, i) && isScrambleOfSubstring(x + i, y, len - i); } } unSet[make_pair(strS1.substr(x, len), strS2.substr(y, len))] = flag; return flag; } private: string strS1, strS2; typedef pair<string, string> PAIR; map<PAIR,bool> unSet; };