Skip to content

Commit

Permalink
Merge 06511a3 into 6f01f38
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Feb 22, 2020
2 parents 6f01f38 + 06511a3 commit bd62e51
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -454,4 +454,5 @@ problems from
* [Day 454](https://github.com/vaskoz/dailycodingproblem-go/issues/917)
* [Day 455](https://github.com/vaskoz/dailycodingproblem-go/issues/919)
* [Day 456](https://github.com/vaskoz/dailycodingproblem-go/issues/921)
* [Day 457](https://github.com/vaskoz/dailycodingproblem-go/issues/923)

28 changes: 28 additions & 0 deletions day457/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package day457

import "reflect"

// StartIndicesAnagrams returns all the starting indices (0-based)
// for the anagrams of W in the longer string S.
// Runs in O(N*M) time where N is len(word) and M is len(str).
func StartIndicesAnagrams(w string, s string) []int {
freq := make(map[rune]int)
for _, r := range w {
freq[r]++
}

var result []int

for i := range s {
sub := make(map[rune]int)
for j := i; j < len(s) && j < i+len(w); j++ {
sub[rune(s[j])]++
}

if reflect.DeepEqual(sub, freq) {
result = append(result, i)
}
}

return result
}
33 changes: 33 additions & 0 deletions day457/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package day457

import (
"reflect"
"testing"
)

// nolint
var testcases = []struct {
W, S string
expected []int
}{
{"ab", "abxaba", []int{0, 3, 4}},
{"ba", "abxaba", []int{0, 3, 4}},
{"aabx", "abxaba", []int{0, 2}},
}

func TestStartIndicesAnagrams(t *testing.T) {
t.Parallel()

for _, tc := range testcases {
if result := StartIndicesAnagrams(tc.W, tc.S); !reflect.DeepEqual(tc.expected, result) {
t.Errorf("Expected %v got %v", tc.expected, result)
}
}
}
func BenchmarkStartIndicesAnagrams(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
StartIndicesAnagrams(tc.W, tc.S)
}
}
}

0 comments on commit bd62e51

Please sign in to comment.