1. 程式人生 > >Leetcode題解:Scramble String

Leetcode題解: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.
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;
    }
};

注意到我使用了一個技巧,使用加權和的方式來判斷字元集合是否相等。

在這裡插入圖片描述