LeetCode – Scramble String (Java)

Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.

Java Solution

public boolean isScramble(String s1, String s2) {
        return false;
    if(s1.length()==0 || s1.equals(s2))
        return true;
    char[] arr1 = s1.toCharArray();
    char[] arr2 = s2.toCharArray();
    if(!new String(arr1).equals(new String(arr2))){
        return false;
    for(int i=1; i<s1.length(); i++){
        String s11 = s1.substring(0, i);
        String s12 = s1.substring(i, s1.length());
        String s21 = s2.substring(0, i);
        String s22 = s2.substring(i, s2.length());
        String s23 = s2.substring(0, s2.length()-i);
        String s24 = s2.substring(s2.length()-i, s2.length());
        if(isScramble(s11, s21) && isScramble(s12, s22))
            return true;
        if(isScramble(s11, s24) && isScramble(s12, s23))
            return true;    
    return false;
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. Steven Fetterly on 2017-1-4

    Could also be solved by using a map.

    1. Compare the length of both strings. They must be equal for s2 to be a scrambled version of s1.
    2. Create a map of characters and integers.
    3. Loop through the first string and increment each character in the map by one.
    4. Loop through the second string and decrement each character in the map by one.
    5. Loop through the first string again and check that each character in the map stores a value of zero. If there is a negative or positive value stored then we know that s2 is not a scrambled version of s1.

    Time complexity is O(n).

Leave a comment