-
Notifications
You must be signed in to change notification settings - Fork 0
/
30.go
64 lines (52 loc) · 1.46 KB
/
30.go
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
package main
func findSubstring(s string, words []string) []int {
result := []int{}
hashMap := make(map[string]int)
// hash map
for _, word := range words {
hashMap[word] += 1
}
wordLength := len(words[0])
for i := 0; i < wordLength; i++ {
result = append(result, slidingWindow(i, s, words, hashMap)...)
}
return result
}
func slidingWindow(left int, s string, words []string, hashMap map[string]int) []int {
result := []int{}
// wordsCount := len(words)
wordLength := len(words[0])
currentHashMap := make(map[string]int)
right := left + wordLength
for right <= len(s) {
current := string(s[right-wordLength : right])
if count, ok := hashMap[current]; ok {
if count > currentHashMap[current] {
currentHashMap[current] += 1
valid := true
for x, y := range hashMap {
if currentHashMap[x] != y {
valid = false
}
}
if valid {
result = append(result, left)
currentHashMap[string(s[left:left+wordLength])] = currentHashMap[string(s[left:left+wordLength])] - 1
left += wordLength
}
} else {
checkIndex := left
for ; string(s[checkIndex:checkIndex+wordLength]) != current && checkIndex < right-wordLength; checkIndex += wordLength {
currentCheck := string(s[checkIndex : checkIndex+wordLength])
currentHashMap[currentCheck] -= 1
}
left = checkIndex + wordLength
}
} else {
left = right
currentHashMap = make(map[string]int)
}
right += wordLength
}
return result
}