Skip to content

Commit

Permalink
day 13 solution
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Sep 4, 2018
1 parent 26557b6 commit e269547
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
32 changes: 32 additions & 0 deletions day13/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package day13

// LongestSubKDistinct returns find the length of the longest substring
// that contains at most k distinct characters.
func LongestSubKDistinct(s string, k int) string {
r := []rune(s)
if len(r) <= k {
return string(r)
}
letters := make(map[rune]int)
var curL, maxL, curR, maxR int
for curR < len(r) {
if _, found := letters[r[curR]]; len(letters) < k || found {
letters[r[curR]]++
curR++
if curR-curL > maxR-maxL {
maxL, maxR = curL, curR
}
} else {
for len(letters) >= k {
if count := letters[r[curL]]; count == 1 {
delete(letters, r[curL])
} else {
letters[r[curL]]--
}
curL++
}
}

}
return string(r[maxL:maxR])
}
31 changes: 31 additions & 0 deletions day13/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package day13

import "testing"

var testcases = []struct {
input string
k int
expected string
}{
{"abcba", 2, "bcb"},
{"aa", 2, "aa"},
{"xyzabababbbbaaaac", 2, "abababbbbaaaa"},
{"xyzabababbbbaaaac", 2, "abababbbbaaaa"},
}

func TestLongestSubKDistinct(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := LongestSubKDistinct(tc.input, tc.k); result != tc.expected {
t.Errorf("Given %v I expected %v but got %v with k %v", tc.input, tc.expected, result, tc.k)
}
}
}

func BenchmarkLongestSubKDistinct(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
LongestSubKDistinct(tc.input, tc.k)
}
}
}

0 comments on commit e269547

Please sign in to comment.