#C8918. Scrambled String Determination
Scrambled String Determination
Scrambled String Determination
You are given two strings, s1
and s2
. Your task is to determine whether s2
is a scrambled version of s1
. A string s2
is said to be a scrambled version of s1
if it can be obtained by recursively splitting s1
into two non-empty substrings and then swapping them. More formally, if s1
is represented as a binary tree by partitioning it into two parts, then s2
is a scrambled string of s1
if it can be produced by swapping the children of some of the non-leaf nodes in this tree.
The transformation can be expressed using the following recurrence:
$$\text{isScramble}(s1, s2) = \begin{cases} \text{true} &\text{if } s1 = s2,\\[6pt] \text{false} &\text{if } sorted(s1) \neq sorted(s2),\\[6pt] \bigvee_{i=1}^{n-1} \Big((\text{isScramble}(s1[:i], s2[:i]) \wedge \text{isScramble}(s1[i:], s2[i:])) \\ \quad \vee \ (\text{isScramble}(s1[:i], s2[-i:]) \wedge \text{isScramble}(s1[i:], s2[:-i]))\Big) &\text{otherwise.} \end{cases}$$
Example 1:
Input: great rgeat</p>Output: true
Example 2:
Input: abcde caebd</p>Output: false
inputFormat
The input consists of two lines. The first line contains the string s1
and the second line contains the string s2
.
Both strings are non-empty and consist of lowercase English letters.
outputFormat
Output a single line: true
if s2
is a scrambled string of s1
; otherwise, output false
.
great
rgeat
true
</p>