87. Scramble String
LeetCode 87. Scramble String
Description
We can scramble a string s to get a string t using the following algorithm:
If the length of the string is 1, stop.
If the length of the string is > 1, do the following: Split the string into two non-empty substrings at a random index, i.e., if the string is
s
, divide it tox
andy
wheres = x + y
. Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step,s
may becomes = x + y
ors = y + x
. * Apply step 1 recursively on each of the two substringsx
andy
.
Given two strings s1
and s2
of the same length , return true
if s2
is a scrambled string of s1
, otherwise, return false
.
Example 1:
Example 2:
Constraints:
s1.length == s2.length
1 <= s1.length <= 30
s1
ands2
consist of lower-case English letters.
Tags
String, Dynamic Programming
Solution
If s2
is scrambled from s1
, we call them harmony. There are some criteria to evaluate whether s1
and s2
are in harmony:
If
s1 == s2
, they are in harmony;If
len(s1) != len(s2)
, they are NOT in harmony;If
s1
ands2
do not share the same (in type and quantity) set of characters, they are NOT in harmony.
In addition to the cases listed above, we consider the split of both strings (see the figure above). Two strings are in harmont if and only if there is a splitting point that:
When
l(s1)
andl(s2)
are not swapped, having thatl(s1)
andl(s2)
are in harmony, andr(s1)
andr(s2)
are in harmony;When
l(s1)
andl(s2)
are swapped, having thatr(s1)
andl(s2)
are in harmony, andl(s1)
andr(s2)
are in harmony.
We can formulate both cases:
Thus, we enumerate every splitting point of substrings and evaluate both cases, and we use a 3D array to memorize the calculated splitting points.
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?