Skip to content

Commit

Permalink
Merge 9da2fd0 into 26557b6
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Sep 4, 2018
2 parents 26557b6 + 9da2fd0 commit 1d9976a
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,4 @@ problems from
* [Day 11](https://github.com/vaskoz/dailycodingproblem-go/issues/23)
* [Day 12](https://github.com/vaskoz/dailycodingproblem-go/issues/25)
* [Day 12 Count and Deepest](https://github.com/vaskoz/dailycodingproblem-go/issues/27)
* [Day 13](https://github.com/vaskoz/dailycodingproblem-go/issues/29)
33 changes: 33 additions & 0 deletions day13/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package day13

// LongestSubKDistinct returns find the length of the longest substring
// that contains at most k distinct characters.
// Runs in O(N) time. Uses O(K) space for the map.
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 1d9976a

Please sign in to comment.