-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0087-scramble-string.go
More file actions
81 lines (62 loc) · 1.52 KB
/
0087-scramble-string.go
File metadata and controls
81 lines (62 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package strings
import "slices"
// https://leetcode.com/problems/scramble-string/
// Approach: Dynamic Programming with Memoization (Top-Down)
// Time: O(n^4) - for each substring pair, try all split points
// Space: O(n^3) - memoization cache
func isScramble(s1 string, s2 string) bool {
// Helper function to check if two strings have the same characters
sameChars := func(s1, s2 string) bool {
if len(s1) != len(s2) {
return false
}
// Sort and compare
r1 := []rune(s1)
r2 := []rune(s2)
slices.Sort(r1)
slices.Sort(r2)
for i := range r1 {
if r1[i] != r2[i] {
return false
}
}
return true
}
// Memoization cache: "s1,s2" -> bool
memo := make(map[string]bool)
var helper func(s1, s2 string) bool
helper = func(s1, s2 string) bool {
// Base cases
if s1 == s2 {
return true
}
// Quick check: if character frequencies don't match, can't be scramble
if !sameChars(s1, s2) {
return false
}
// Check memo
key := s1 + "," + s2
if val, exists := memo[key]; exists {
return val
}
// Try all possible split points
n := len(s1)
for i := 1; i < n; i++ {
// Case 1: No swap
// s1[:i] matches s2[:i] AND s1[i:] matches s2[i:]
if helper(s1[:i], s2[:i]) && helper(s1[i:], s2[i:]) {
memo[key] = true
return true
}
// Case 2: Swap
// s1[:i] matches s2[n-i:] AND s1[i:] matches s2[:n-i]
if helper(s1[:i], s2[n-i:]) && helper(s1[i:], s2[:n-i]) {
memo[key] = true
return true
}
}
memo[key] = false
return false
}
return helper(s1, s2)
}