Fork me on GitHub

87. Scramble String

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.

解析

题意在于判断一个字符串是否为另一个字符串“乱序”得到,这种乱序采用的方式是将一个字符串从某个位置“割开”,形成两个子串,然后对两个子串进行同样的“割开”操作,直到到达叶子节点,无法再分割。然后对非叶子节点的左右孩子节点进行交换,最后重新从左至右组合形成新的字符串,由于这个过程中存在字符位置的变化,因此,原来的字符串顺序可能会被打乱,当然也可能没有(同一个非叶子节点的左右孩子交换0次或偶数次,就无变化)。需要注意的点:

1、原字符串每次被割开的位置并不确定可能为[1,s.size()-1],所以必然需要遍历所有可能割开的位置;

2、原字符串从第i个位置被割开(i在区间[1,s.size()-1]),形成的两个子串s.substr(0,i)和s.substr(i,s.size()-i),如果这两个子串不全为空,则它们的母串(这里指原字符串)就是所谓的非叶子节点,这两个子串可以左右交换(按照二叉树的展开方式);对于两个子串,可继续割裂,直到形成叶子节点。
// 87. Scramble String
class Solution_87 {
public:
	bool isScramble(string s1, string s2) {

		if (s1==s2)
		{
			return true;
		}
		if (s1.size()!=s2.size())
		{
			return false;
		}

		vector<int> hash(26,0);
		for (int i = 0; i < s1.size();i++)
		{
			hash[s1[i] - 'a']++;
			hash[s2[i] - 'a']--;
		}
		for (int i = 0; i < 26;i++)  //递归剪枝
		{
			if (hash[i]!=0)
			{
				return false;
			}
		}

		bool res = false;
		for (int i = 1; i < s1.size();i++) //遍历所有可能割开的位置, 切割的长度
		{
			res = res || (isScramble(s1.substr(0, i), s2.substr(0, i)) && isScramble(s1.substr(i, s1.size() - i), s2.substr(i, s1.size() - i)));   //长度要一致
			res = res || (isScramble(s1.substr(0, i), s2.substr(s1.size() - i)) && isScramble(s1.substr(i),s2.substr(0, s1.size()-i)));
		}

		return res;

	}
};


题目来源

posted @ 2018-04-10 21:41  ranjiewen  阅读(162)  评论(0编辑  收藏  举报