Created
August 27, 2020 01:26
-
-
Save cunla/6fbe9cdced74ed20816b46263bfc619b to your computer and use it in GitHub Desktop.
Is one string a scramble of another string (leetcode)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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