Scramble String
Given 2 strings of same length, determine if s2 is the scramble of s1.
Scramble is when a string is represented as a binary tree, swap left and right children of some node and we get a new string. We say that the new one is the scramble of the original one.
Solution:
1. the two string must have the same length and all characters in these two strings must be the same. So we use a Integer array of 26 as a hashset to see if the characters of them are totally same.
2. Then we just need to check if their two children node can be scrambled. If s1.leftsubstring is scramble of s2.leftsubstring && s1.rightsubstring is scramble of s2.rightsubstring. Or if s1.leftsubstring is scramble of s2.rightsubstring && s1. rightsubstring is scramble of s2.leftsubstring, we can return true. So just recursive revoke this function and make sure the length of the substring we compare each time is the same.
Code:
public class Solution { public boolean isScramble(String s1, String s2) { if(s1.equals(s2)) return true; if(s1.length()!=s2.length()) return false; int[] arr = new int[26]; for(int i = 0; i < s1.length(); i++){ arr[s1.charAt(i)-'a']++; arr[s2.charAt(i)-'a']--; } for(int i : arr){ if(i!=0) return false; } for(int i = 1; i<s1.length(); i++){ if(isScramble(s1.substring(0,i), s2.substring(0,i)) && isScramble(s1.substring(i),s2.substring(i))) return true; if(isScramble(s1.substring(0,i), s2.substring(s2.length()-i)) && isScramble(s1.substring(i), s2.substring(0,s2.length()-i))) return true; } return false; } }

浙公网安备 33010602011771号