Skip to content

Commit 6b07fe9

Browse files
solves scramble strings (#87) in python
1 parent 1842d27 commit 6b07fe9

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

python/scramble_strings.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# https://leetcode.com/problems/scramble-string/description/
2+
# T: O(n^4) where n is the number of characters in the string
3+
# S: O(n^3) where n is the number of characters in the string
4+
5+
from collections import defaultdict
6+
7+
class Solution:
8+
def isScramble(self, s1: str, s2: str) -> bool:
9+
cache = dict()
10+
return self.helper(s1, s2, cache)
11+
12+
def helper(self, s1: str, s2: str, cache: dict) -> bool:
13+
key = (s1,s2)
14+
key_r = (s2,s1)
15+
if key in cache:
16+
return cache[key]
17+
if key_r in cache:
18+
return cache[key_r]
19+
# If not cached
20+
n = len(s1)
21+
# Base case
22+
if sorted(s1) != sorted(s2):
23+
cache[key] = False
24+
return False
25+
if n <= 3:
26+
cache[key] = True
27+
return True
28+
# split sting for comparision
29+
count_s1 = defaultdict(int)
30+
count_s2 = defaultdict(int)
31+
count_s2_r = defaultdict(int)
32+
33+
for i in range(1, n):
34+
count_s1[s1[i-1]] += 1
35+
count_s2[s2[i-1]] += 1
36+
count_s2_r[s2[-i]] += 1
37+
38+
if count_s1 == count_s2:
39+
cache[key] = self.helper(s1[0:i], s2[0:i], cache) and self.helper(s1[i:n], s2[i:n], cache)
40+
if cache[key]:
41+
return True
42+
if count_s1 == count_s2_r:
43+
cache[key] = self.helper(s1[0:i], s2[n-i:n], cache) and self.helper(s1[i:n], s2[0:n-i], cache)
44+
if cache[key]:
45+
return True
46+
return False

0 commit comments

Comments
 (0)