[LeetCode] [Java] Scramble String
Question:
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 nodegrAnd swap its two children, it produces a scrambled stringrgeat.
rgeat / rg eat / / r g e at / a t
We say thatrgeatIs a scrambled stringgreat.
Similarly, if we continue to swap the children of nodeseatAndat, It produces a scrambled stringrgtae.
rgtae / rg tae / / r g ta e / t a
We say thatrgtaeIs a scrambled stringgreat.
Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.
Question:
Given the string s1, We Can recursively divide it into two non-empty subsets in the form of a binary tree.
Below is s1 =greatA possible representation:
great / gr eat / / g r e at / a t
In the process of concatenating strings, we can select any non-leaf node and exchange its two children.
For example, if we select a nodegrAnd swap it with two children, which will generate a patchwork characterrgeat.
rgeat / rg eat / / r g e at / a t
We will
Rgeat is calledgreat.
Similarly, if we continue to exchange child nodeseatAndat,This will generate a patchwork characterrgtae.
rgtae / rg tae / / r g ta e / t a
We call rgtae a similar string of great.
Determine whether s2 is a similar string of S1.
Algorithm analysis:
* The method to deal with complex problems is to consider simple special cases to find out the rules.
* First, let's look at the simple situation:
* String Length: 1. Obviously, the two strings must be identical.
* String Length: 2: When s1 = AB, s2 can only be AB or ba.
* For strings of any length, we can divide s1 into a1 and b1. s2 is divided into a2 and b2 to meet (a1 ~ A2) & (b1 ~ B2) or (a1 ~ B2) & (a2 ~ B1 ))
* In this way, we have found a solution to the problem. First, we try to use recursion to write.
(Recursion ):
* A prerequisite for similarity between two strings is that they contain the same character set. The simple method is to sort the characters of the two strings and then compare whether they are the same.
* This check can greatly reduce the number of recursion times.
AC code:
public class Solution {public boolean isScramble(String s1, String s2) { int l1 = s1.length(); int l2 = s2.length(); if(l1!=l2) { return false; } if(l1==0) { return true; } char[] c1 = s1.toCharArray(); char[] c2 = s2.toCharArray(); if(l1==1) { return c1[0]==c2[0]; } Arrays.sort(c1); Arrays.sort(c2); for(int i=0;i