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) { if(s1.length()!=s2.length()) return false;   if(s1.length()==0 || s1.equals(s2)) return true;   char[] arr1 = s1.toCharArray(); char[] arr2 = s2.toCharArray(); Arrays.sort(arr1); Arrays.sort(arr2); 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:
```<pre><code>
String foo = "bar";
</code></pre>
```
• Steven Fetterly

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).