This is the first in a series of coding challenges for golang developers. We'll start easy, so let's get started.
Write a golang function to compute the maximum number of unique characters in a string.
package main
import (
"fmt"
)
func main() {
str := "Hello, World!"
maxUnique := maxUniqueCharacters(str)
fmt.Printf("The string \"%s\" contains %d unique characters.\n", str, maxUnique)
}
func maxUniqueCharacters(str string) int {
charSet := make(map[rune]bool)
for _, char := range str {
charSet[char] = true
}
return len(charSet)
}
The solution makes use of a map[rune]bool
to indicate the presence of a given rune. The value in the map acts as a logical or if there are multiple occurrences of a given rune. So once a given rune is found, it is not added to the map again.
Once the string is completely scanned, the length of the map is the number of unique characters in the string.
How can this be improved? Post your thoughts in the comments.
Thanks!
The code for this post and all posts in this series can be found here
Top comments (0)