Question

Formatted question description: https://leetcode.ca/all/87.html

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.

@tag-dp

Algorithm

DFS

If s1 and s2 are scramble, then there must be a length l1 on s1, which divides s1 into s11 and s12, and there are also s21 and s22, then either s11 and s21 are scramble and s12 and s22 are scramble; or s11 and s22 are scramble and s12 and s21 are scramble.

Take the example of rgeat and great in the title. rgeat can be divided into rg and eat, and great can be divided into gr and eat. rg and gr are scrambled, and eat and eat are of course scrambled.

DP

For the subject of three-dimensional dynamic programming, use a three-dimensional array dp[i][j][n], where i is the starting character of s1, j is the starting character of s2, and n is the current string length, dp[i ][j][len] indicates whether the string with length len starting from i and j as s1 and s2 are scrambles for each other.

With the dp array, let’s look at the state transition equation, which is how to get dp[i][j][len] based on historical information. To judge whether this is satisfied, first split the current s1[i…i+len-1] string into two parts, and then divide into two cases:

  • the first is the left side and s2[j…j+ len-1] Is the left part a scramble, and whether the right part and s2[j…j+len-1] is a scramble;
  • the second case is the left part and s2[j…j+len-1] Whether the right part is a scramble, and whether the right part and the left part of s2[j…j+len-1] is a scramble.
    • If one of the above two conditions is true, it means that s1[i…i+len-1] and s2[j…j+len-1] are scramble. There is historical information for judging whether these left and right parts are scramble, because all the cases where the length is less than n have been solved before (that is, the length is the outermost loop).

The above is the case of splitting. For s1[i…i+len-1], there are len-1 splitting methods. As long as one of these splitting methods is established, then the two strings are scramble. In summary, the state transition equation is:

`dp[i][j][len] =   (dp[i][j][k] && dp[i+k][j+k][len-k]   dp[i][j+len-k][k] && dp[i+k][j][len-k])

Code

Java

  • 
    public class Scramble_String {
    
    	public class Solution {
    	    public boolean isScramble(String s1, String s2) {
    	        if (s1 == null || s2 == null || s1.length() != s2.length()) {
    	            return false;
    	        }
    
    	        int len = s1.length();
    
    	        // dp[i][j], i,j not index, substring i to j of s1/s2 are scrambled
    	        boolean[][][] dp = new boolean[len][len][len + 1];
    
    	        for (int i = 0; i < len; i++) {
    	            for (int j = 0; j < len; j++) {
    	                dp[i][j][1] = s1.charAt(i) == s2.charAt(j);
    	            }
    	        }
    
    	        for (int n = 1; n < len + 1; n++) {
    	            for (int i = 0; i + n - 1 < len; i++) { // @note: here boundary check, I missed
    	                for (int j = 0; j + n - 1 < len; j++) {
    
    	                    for (int sublen = 1; sublen < n; sublen++) {
    
    	                        // same strings: s1="abcde", s2="abcde"
    	                        boolean ifSame = dp[i][j][sublen] && dp[i + sublen][j + sublen][n - sublen];
    
    	                        // swapped strings: s1="abcde", s2="cdeab"
    	                        // @note: especially for the index here, using an example for assistance
    	                        boolean ifSwapped = dp[i][j + n - sublen][sublen] && dp[i + sublen][j][n - sublen];
    
    	                        // dp[i][j][n] = ifSame || ifSwapped; // @note: stupid...being overwritten
    	                        if (ifSame || ifSwapped) {
    	                            dp[i][j][n] = true;
    	                            break;
    	                        }
    	                    }
    	                }
    	            }
    	        }
    
    	        return dp[0][0][len];
    
    	    }
    	}
    
    	public class Solution_over_time { // clearly a lot of repeated calculation during recursion
    	    public boolean isScramble(String s1, String s2) {
    	        if (s1 == null || s2 == null || s1.length() != s2.length()) {
    	            return false;
    	        }
    
    	        if (s1.length() == 0) {
    	            return s2.length() == 0;
    	        }
    
    	        if (s1.length() == 1) {
    	            return s1.charAt(0) == s2.charAt(0);
    	        }
    
    	        // basically swap happens for a node of 2 children
    	        if (s1.length() == 2) {
    	            boolean isSame = s1.equals(s2);
    	            boolean isSwapped = s1.charAt(0) == s2.charAt(1) && s1.charAt(1) == s2.charAt(0);
    
    	            return isSame || isSwapped;
    	        }
    
    	        for (int i = 1; i < s1.length(); i++) {
    
    	            // @note: left and right child chould NOT be empty
    	            // int splitIndex = i;
    	            boolean isThisScramble = isScramble(s1.substring(0, i), s2.substring(0, i))
    	                                        && isScramble(s1.substring(i), s2.substring(i));
    	            if (isThisScramble) {
    	                return true;
    	            }
    	        }
    
    	        return false;
    
    	    }
    	}
    
    }
    
  • // OJ: https://leetcode.com/problems/scramble-string
    // Time: O(N^(N+1))
    // Space: O(N^(N+1))
    class Solution {
    public:
        bool isScramble(string s1, string s2) {
            if (s1.size() != s2.size()) return false;
            if (s1 == s2) return true;
            for (int i = 1; i < s1.size(); ++i) {
                string l1 = s1.substr(0, i), r1 = s1.substr(i);
                string l2 = s2.substr(0, i), r2 = s2.substr(i);
                string r2r = s2.substr(0, s1.size() - i), l2r = s2.substr(s1.size() - i);
                if ((isScramble(l1, l2) && isScramble(r1, r2))
                   || (isScramble(l1, l2r) && isScramble(r1, r2r))) return true;
            }
            return false;
        }
    };
    
  • class Solution(object):
      def isScramble(self, s1, s2):
        """
        :type s1: str
        :type s2: str
        :rtype: bool
        """
        n = len(s1)
        m = len(s2)
        if sorted(s1) != sorted(s2):
          return False
    
        if n < 4 or s1 == s2:
          return True
    
        for i in range(1, n):
          if self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]):
            return True
          if self.isScramble(s1[:i], s2[-i:]) and self.isScramble(s1[i:], s2[:-i]):
            return True
        return False
    
    

All Problems

All Solutions