Leetcode题解:Scramble String

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jining11/article/details/84194589

题目要求

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.

Example 1:

Input: s1 = "great", s2 = "rgeat"
Output: true
Example 2:

Input: s1 = "abcde", s2 = "caebd"
Output: false

解题思路

最重要的事情就是——不要被题目吓倒,别想太多关于树的事情,我们只需要好好分析,这种字符串有什么特性。

  • 第一点显而易见,如果一个字符串的前某个部分和另一个字符串对应部分呈颠倒关系,后面剩下的部分与另一个字符串对应部分呈颠倒关系,那么这两个字符串呈颠倒关系,并且分割的两个点是树的根节点的两个孩子,并且这两个孩子没有经历交换。
  • 第二点,考虑根节点两个孩子交换之后的情况。
  • 对于长度小于4的字符串s1, s2,只要判断它们所包含的字符一致,就可以直接判定是呈颠倒关系的。

源码

class Solution {
public:

	//判断两个字符串是否拥有相同字符
	bool is_have_same_char(string s1, string s2) {
		if (s1.size() != s2.size()) {
			return false;
		}
		long sum1 = 0, sum2 = 0;
		for (int i = 0; i < s1.size(); i++) {
			sum1 += (s1[i]-'a')*((s1[i]-'a')+29);
			sum2 += (s2[i]-'a')*((s2[i]-'a')+29);
		}
		return sum1 == sum2;
	}


    bool isScramble(string s1, string s2) {
    	if (s1 == s2) {
    		return true;
    	}
        if (!is_have_same_char(s1, s2)) {
        	return false;
        }
        if (s1.size() < 4) {
        	return true;
        }
        for (int i = 1; i < s1.size(); i++) {
        	if (isScramble(s1.substr(0, i), s2.substr(0, i)) && isScramble(s1.substr(i), s2.substr(i))) {
        		return true;
        	}
        	if (isScramble(s1.substr(0, i), s2.substr(s1.size()-i)) && isScramble(s1.substr(i), s2.substr(0, s1.size()-i))) {
        		return true;
        	}
        }
        return false;
    }
};

注意到我使用了一个技巧,使用加权和的方式来判断字符集合是否相等。

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/jining11/article/details/84194589
今日推荐