diff --git a/ch01/01_is_unique.go b/ch01/01_is_unique.go index cee9c4a..5b915a3 100644 --- a/ch01/01_is_unique.go +++ b/ch01/01_is_unique.go @@ -1,5 +1,7 @@ package ch01 +import "strings" + // IsUnique determine if a string has all unique chars // This solution is based on HashTable (Go map) data structure func IsUnique(s string) bool { @@ -30,3 +32,20 @@ func IsUniqueVanilla(s string) bool { return true } + +// IsUniqueBits determines if a string has all unique chars (only works for ASCII) +// This solution doesn't utilize any additional data structures and has O(n) time complexity +func IsUniqueBits(s string) bool { + + s = strings.ToLower(s) + var vector int32 + for _, rune := range s { + index := rune - 'a' + mask := int32(1 << index) + if (vector & mask) == mask { + return false + } + vector = vector | mask + } + return true +} diff --git a/ch01/01_is_unique_test.go b/ch01/01_is_unique_test.go index 5734dd0..d6a6185 100644 --- a/ch01/01_is_unique_test.go +++ b/ch01/01_is_unique_test.go @@ -21,3 +21,13 @@ func TestIsUniqueVanilla(t *testing.T) { t.Error("'uniqke' is a unique string") } } + +func TestIsUniqueBits(t *testing.T) { + if IsUniqueBits("unique") { + t.Error("'unique' is not a unique string") + } + + if !IsUniqueBits("uniqke") { + t.Error("'uniqke' is a unique string") + } +} diff --git a/ch01/03_urlify.go b/ch01/03_urlify.go index d9a8682..2e3b029 100644 --- a/ch01/03_urlify.go +++ b/ch01/03_urlify.go @@ -1,5 +1,7 @@ package ch01 +import "regexp" + // URLifyn returns the string with HTML encoded spacese // Expects real string length as a second parameter func URLifyn(s string, n int) string { @@ -55,3 +57,11 @@ func URLify(s string) string { return string(runes) } + +// UrlifyRegex returns the s string with HTML-encoded space characters. +func UrlifyRegex(s string) string { + + exp := regexp.MustCompile(" ") + return exp.ReplaceAllString(s, "%20") + +} diff --git a/ch01/03_urlify_test.go b/ch01/03_urlify_test.go index 4db9a15..0969f54 100644 --- a/ch01/03_urlify_test.go +++ b/ch01/03_urlify_test.go @@ -15,3 +15,10 @@ func TestUrlify(t *testing.T) { t.Errorf("Expected \"%s\" after ULRification, got \"%s\"", expected, actual) } } + +func TestUrlifyRegex(t *testing.T) { + actual, expected := UrlifyRegex("slug url"), "slug%20url" + if actual != expected { + t.Errorf("Expected \"%s\" after ULRification, got \"%s\"", expected, actual) + } +}