"Substring With Concatenation of all words" hard task No 30 accepted solution
This commit is contained in:
52
30-substring-with-concatenation-of-all-words.go
Normal file
52
30-substring-with-concatenation-of-all-words.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
func FindSubstring(s string, words []string) []int {
|
||||
|
||||
res := []int{}
|
||||
|
||||
numWords := len(words)
|
||||
strLen := len(s)
|
||||
|
||||
if numWords == 0 || strLen == 0 {
|
||||
return res
|
||||
}
|
||||
|
||||
wordMapOriginal := map[string]int{}
|
||||
for _, w := range words {
|
||||
wordMapOriginal[w]++
|
||||
}
|
||||
|
||||
jsonWordMapOriginal, _ := json.Marshal(wordMapOriginal)
|
||||
|
||||
wordSz := len(words[0])
|
||||
wndSz := numWords * wordSz
|
||||
|
||||
for i := 0; i <= strLen-wndSz; i++ {
|
||||
j := 0
|
||||
|
||||
wordMap := map[string]int{}
|
||||
|
||||
for j = i; j < i+wndSz; j += wordSz {
|
||||
word := s[j : j+wordSz]
|
||||
_, ok := wordMapOriginal[word]
|
||||
if !ok {
|
||||
break
|
||||
} else {
|
||||
wordMap[word]++
|
||||
}
|
||||
}
|
||||
if j == i+wndSz {
|
||||
jsonWordMap, _ := json.Marshal(wordMap)
|
||||
if bytes.Compare(jsonWordMap, jsonWordMapOriginal) == 0 {
|
||||
res = append(res, i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
Reference in New Issue
Block a user