Skip to content

Commit 99e401f

Browse files
committed
Time: 265 ms (5.11%), Space: 18.4 MB (59.09%) - LeetHub
1 parent 2f2814c commit 99e401f

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# time complexity: O(n^4)
2+
# space complexity: O(n^3)
3+
class Solution:
4+
def isScramble(self, s1: str, s2: str) -> bool:
5+
n = len(s1)
6+
dp = [[[False for _ in range(n)] for _ in range(n)]
7+
for _ in range(n + 1)]
8+
for i in range(n):
9+
for j in range(n):
10+
dp[1][i][j] = s1[i] == s2[j]
11+
for length in range(2, n + 1):
12+
for i in range(n + 1 - length):
13+
for j in range(n + 1 - length):
14+
for newLength in range(1, length):
15+
dp1 = dp[newLength][i]
16+
dp2 = dp[length - newLength][i + newLength]
17+
dp[length][i][j] |= dp1[j] and dp2[j + newLength]
18+
dp[length][i][j] |= (
19+
dp1[j + length - newLength] and dp2[j])
20+
return dp[n][0][0]
21+
22+
23+
s1 = "great"
24+
s2 = "rgeat"
25+
print(Solution().isScramble(s1, s2))
26+
s1 = "abcde"
27+
s2 = "caebd"
28+
print(Solution().isScramble(s1, s2))
29+
s1 = "a"
30+
s2 = "a"
31+
print(Solution().isScramble(s1, s2))

0 commit comments

Comments
 (0)