-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathleetcode0030.go
68 lines (59 loc) · 1.36 KB
/
leetcode0030.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
65
66
67
68
/*
LeetCode 30: https://leetcode.com/problems/substring-with-concatenation-of-all-words/
*/
package leetcode
func findSubstring(s string, words []string) []int {
wordToCount := make(map[string]int)
total := 0
for _, word := range words {
total += len(word)
if _, exists := wordToCount[word]; exists {
wordToCount[word]++
} else {
wordToCount[word] = 1
}
}
result := make([]int, 0)
if len(s) < total || len(s) == 0 || total == 0 {
return result
}
bytes, counts, length := []byte(s), len(words), len(words[0])
for i := 0; i < length; i++ {
clone := make(map[string]int)
for key, val := range wordToCount {
clone[key] = val
}
matched := 0
for j := 0; j < counts-1; j++ {
start := j*length + i
word := string(bytes[start : start+length])
if count, exists := clone[word]; exists {
clone[word]--
if count > 0 {
matched++
}
}
}
for j := i + length*(counts-1); j <= len(s)-length; j += length {
word := string(bytes[j : j+length])
if count, exists := clone[word]; exists {
clone[word]--
if count > 0 {
matched++
}
}
start := j - length*(counts-1)
if matched == counts {
result = append(result, start)
}
word = string(bytes[start : start+length])
if count, exists := clone[word]; exists {
clone[word]++
if count >= 0 {
matched--
}
}
}
}
return result
}