[LeetCode] -*** Recursion/DP – Scramble String — 2015-05-29

[LeetCode] -*** Recursion/DP – Scramble String

Problem:

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.

Reference 1: http://blog.csdn.net/linhuanmars/article/details/24506703

Reference 2: http://www.cnblogs.com/springfor/p/3896164.html

Method 1: by recursive.

  • Partition s1 as s11, s12; partition s2 as s21, s22. Then s11, s21 should be scramble and s12, s22 should be scramble; or s11, s22 are scramble and s12, s21 are scramble.
  • To avoid the exceeding time limit. Check: 1) length equal? (If not, false) 2) They contain same elements? (if not, false)3) they are equal?(if yes, true)

Code for method 1:

public class Solution {
    public boolean isScramble(String s1, String s2) {
        if (s1.length()!= s2.length()) return false;
        if (s1.length() == 0) return s2.length() == 0;
        if (s1.equals(s2)) return true;
        // Pruning to pass it!
        char[] t1 = s1.toCharArray(), t2 = s2.toCharArray();
        Arrays.sort(t1);
        Arrays.sort(t2);
        if (!new String(t1).equals(new String(t2)))  return false;
        
        for (int i = 0; i < s1.length()-1; i++){
            //partition s1 into two pieces;
            String s11 = s1.substring(0,i+1);
            String s12 = s1.substring(i+1);
        
            String s21 = s2.substring(0,i+1);
            String s22 = s2.substring(i+1);
            if ((isScramble(s11,s21)&&isScramble(s12,s22) )) {
                return true;
            }
            
            s21 = s2.substring(s2.length()-i-1);
            s22 = s2.substring(0,s2.length()-i-1);
            if ((isScramble(s11,s21)&&isScramble(s12,s22) )) {
                return true;
            }
            
        }
        return false;
    }
}

Method 2:  by Dp 

Code for method 2: