From 9ebb71d76fdb70cd461120ed4ef9143a6427b3b1 Mon Sep 17 00:00:00 2001 From: Rostislav Kuratch Date: Wed, 20 Apr 2022 16:42:03 +0300 Subject: [PATCH] "Substring With Concatenation of all words" hard task No 30 accepted solution --- ...bstring-with-concatenation-of-all-words.go | 52 +++++++++++++++++++ ...ng-with-concatenation-of-all-words_test.go | 33 ++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 30-substring-with-concatenation-of-all-words.go create mode 100644 30-substring-with-concatenation-of-all-words_test.go diff --git a/30-substring-with-concatenation-of-all-words.go b/30-substring-with-concatenation-of-all-words.go new file mode 100644 index 0000000..8feb983 --- /dev/null +++ b/30-substring-with-concatenation-of-all-words.go @@ -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 +} diff --git a/30-substring-with-concatenation-of-all-words_test.go b/30-substring-with-concatenation-of-all-words_test.go new file mode 100644 index 0000000..92b95ca --- /dev/null +++ b/30-substring-with-concatenation-of-all-words_test.go @@ -0,0 +1,33 @@ +package main + +import ( + "github.com/stretchr/testify/assert" + "testing" +) + +func TestFindSubstring128(t *testing.T) { + words := []string{"word", "good", "best", "good"} + expected := []int{8} + res := FindSubstring("wordgoodgoodgoodbestword", words) + assert.Equal(t, expected, res) +} + +func TestFindSubstring0(t *testing.T) { + words := []string{"foo", "bar"} + expected := []int{0, 9} + res := FindSubstring("barfoothefoobarman", words) + assert.Equal(t, expected, res) +} + +func TestFindSubstring1(t *testing.T) { + words := []string{"word", "good", "best", "word"} + expected := []int{} + res := FindSubstring("wordgoodgoodgoodbestword", words) + assert.Equal(t, expected, res) +} +func TestFindSubstring2(t *testing.T) { + words := []string{"bar", "foo", "the"} + expected := []int{6, 9, 12} + res := FindSubstring("barfoofoobarthefoobarman", words) + assert.Equal(t, expected, res) +}