Skip to content

Instantly share code, notes, and snippets.

@cunla
Created August 27, 2020 01:26
Show Gist options
  • Save cunla/6fbe9cdced74ed20816b46263bfc619b to your computer and use it in GitHub Desktop.
Save cunla/6fbe9cdced74ed20816b46263bfc619b to your computer and use it in GitHub Desktop.
Is one string a scramble of another string (leetcode)
def is_scramble(s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
if len(s1) == 0 or s1 == s2:
return True
sorted_s1 = sorted(s1)
sorted_s2 = sorted(s2)
if sorted_s1 != sorted_s2:
return False
for i in range(1, len(s1)):
if is_scramble(s1[:i], s2[:i]) and is_scramble(s1[i:], s2[i:]):
return True
rest = len(s2) - i
if is_scramble(s1[:i], s2[rest:]) and is_scramble(s1[i:], s2[:rest]):
return True
return False
if __name__ == '__main__':
assert is_scramble("gr", "rg")
assert is_scramble("great", "rgeat")
assert not is_scramble("abcde", "caebd")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment