forked from halfrost/LeetCode-Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path30. Substring with Concatenation of All Words.go
49 lines (46 loc) · 1.19 KB
/
30. Substring with Concatenation of All Words.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
package leetcode
func findSubstring(s string, words []string) []int {
if len(words) == 0 {
return []int{}
}
res := []int{}
counter := map[string]int{}
for _, w := range words {
counter[w]++
}
length, totalLen, tmpCounter := len(words[0]), len(words[0])*len(words), copyMap(counter)
for i, start := 0, 0; i < len(s)-length+1 && start < len(s)-length+1; i++ {
//fmt.Printf("sub = %v i = %v lenght = %v start = %v tmpCounter = %v totalLen = %v\n", s[i:i+length], i, length, start, tmpCounter, totalLen)
if tmpCounter[s[i:i+length]] > 0 {
tmpCounter[s[i:i+length]]--
//fmt.Printf("******sub = %v i = %v lenght = %v start = %v tmpCounter = %v totalLen = %v\n", s[i:i+length], i, length, start, tmpCounter, totalLen)
if checkWords(tmpCounter) && (i+length-start == totalLen) {
res = append(res, start)
continue
}
i = i + length - 1
} else {
start++
i = start - 1
tmpCounter = copyMap(counter)
}
}
return res
}
func checkWords(s map[string]int) bool {
flag := true
for _, v := range s {
if v > 0 {
flag = false
break
}
}
return flag
}
func copyMap(s map[string]int) map[string]int {
c := map[string]int{}
for k, v := range s {
c[k] = v
}
return c
}