Welcome to Subscribe On Youtube

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

To determine if two strings s1 and s2 are scramble, there must exist a length l1 in s1 such that it can be divided into s11 and s12. Similarly, there must exist s21 and s22 such that either s11 and s21 are scramble and s12 and s22 are scramble, or s11 and s22 are scramble and s12 and s21 are scramble.

Consider the example of “rgeat” and “great”. “rgeat” can be divided into “rg” and “eat”, and “great” can be divided into “gr” and “eat”. Since “rg” and “gr” are scrambled and “eat” and “eat” are identical, “rgeat” and “great” are scrambled strings.

DP

To use dynamic programming for this problem, create a three-dimensional array dp[i][j][n], where i represents the starting character of s1, j represents the starting character of s2, and n represents the current string length. dp[i][j][len] indicates whether the substring of s1 and s2 with length len starting from i and j, respectively, are scrambles of each other.

To determine dp[i][j][len], consider the historical information available. Any string with length less than n has already been determined. Divide the current s1[i...i+len-1] string into two parts, and then evaluate the following two cases:

  • The first case is where the left part of s1[i...i+len-1] is a scramble of s2[j...j+len-1] and the right part of s1[i...i+len-1] is a scramble of s2[j...j+len-1].
  • The second case is where the left part of s1[i...i+len-1] is a scramble of s2[j+len-k...j+len-1] and the right part of s1[i...i+len-1] is a scramble of s2[j...j+len-k-1].

If either of the two cases is true, then s1[i...i+len-1] and s2[j...j+len-1] are scramble.

There are len-1 possible splitting methods for s1[i...i+len-1]. If any of these splitting methods yield a true value for the state transition equation, then the two strings are scramble. 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:
        def isScramble(self, s1: str, s2: str) -> bool:
            n = len(s1)
            dp = [[[False] * (n + 1) for _ in range(n)] for _ in range(n)]
            for i in range(n):
                for j in range(n):
                    dp[i][j][1] = s1[i] == s2[j]
            for l in range(2, n + 1):
                for i1 in range(n - l + 1):
                    for i2 in range(n - l + 1):
                        for i in range(1, l):
                            if dp[i1][i2][i] and dp[i1 + i][i2 + i][l - i]:
                                dp[i1][i2][l] = True
                                break
                            if dp[i1][i2 + l - i][i] and dp[i1 + i][i2][l - i]:
                                dp[i1][i2][l] = True
                                break
            return dp[0][0][n]
    
    ############
    
    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