/87. Scramble String

87. Scramble String

Hard
Strings44.1% acceptance

Given two strings source_string and target_string of equal length, determine if target_string can be obtained from source_string by recursively splitting source_string into two non-empty substrings, optionally swapping them, and repeating the process on each substring. Return True if target_string is a scrambled string of source_string, otherwise return False.

Example 1

Input: source_string = listen, target_string = enlist

Output: False

Explanation: Although enlist is an anagram of listen, it cannot be obtained by the described scrambling process.

Example 2

Input: source_string = abc, target_string = bac

Output: True

Explanation: Split abc into a and bc, swap to get bc+a, then split bc into b and c, swap to get c+b, so final string is cba, but bac can be obtained by splitting abc into ab and c, swap to get c+ab, then split ab into a and b, swap to get b+a, so final string is cba. Actually, bac can be obtained by splitting abc into b and ac, then swap to get acb, but bac can be obtained by splitting abc into a and bc, swap to get bc+a, then split bc into b and c, keep order to get b+c, so final string is bca, but bac can be obtained by splitting abc into b and ac, keep order to get b+ac, then split ac into a and c, swap to get c+a, so final string is bca. Actually, bac can be obtained by splitting abc into b and ac, keep order to get b+ac, then split ac into a and c, keep order to get a+c, so final string is bac.

Example 3

Input: source_string = aabb, target_string = bbaa

Output: True

Explanation: Split aabb into aa and bb, swap to get bb+aa.

Constraints

  • 1 <= len(source_string) <= 30
  • len(source_string) == len(target_string)
  • source_string and target_string consist of lowercase English letters
Python (current runtime)

Case 1

Input: source_string = 'abcd', target_string = 'bdac'

Expected: False

Case 2

Input: source_string = 'aabc', target_string = 'abac'

Expected: True

Case 3

Input: source_string = 'xyz', target_string = 'zxy'

Expected: True

Case 4

Input: source_string = 'aaaa', target_string = 'aaaa'

Expected: True

Case 5

Input: source_string = 'mnop', target_string = 'ponm'

Expected: True