-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} |