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; } |
see geeks, better explan.
Explanation of the solution
If string s1 and s2 are scramble strings, there must be a point that breaks s1 to two parts s11, s12, and a point that breaks s2 to two parts, s21, s22, and isScramble(s11, s21) && isScramble(s12, s22) is true, or isScramble(s11, s22) && isScramble(s12, s21) is true.
So we can make it recursively. We just break s1 at different position to check if there exists one position satisfies the requirement.
Some checks are needed otherwise it will time out. For example, if the lengths of two strings are different, they can’t be scramble. And if the characters in two strings are different, they can’t be scramble either.
Well yes, the method suggested by Steven wont work, but just wanted to point out that “tea” is indeed a scrambled “eat” (just break into-“ea” & “t”, and conjoin as “t” & “ea” or, “tea”)
This will not work. Thats essentially sorting both the strings and comparing if equal but the question is not that simple.
Take “eat” as example. There are 6 permutations – “eat”, “eta”, “ate”, “aet”, “tea”, “tae”
but if you draw a tree you’ll see that the valid are limited for a specific configuration: For example, if you breat always from middle – “eat”, “eta”, “ate”, “tae”
And if you’ll solve it using your method, “eat” and “tea” will yield true where as it is false.
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).