We can determine the frequency of unique characters in a given string using the map data structure provided by Go. A map is a collection of (key: value) pairs, where in this case, each unique character in the string serves as a key. The corresponding value represents the count of occurrences for that character. The make
function is used to construct an array or map.
Let's consider an example where we input the string "Hello". In this case, we would expect the following results.
package mainimport ("fmt")func countCharacters(str string) map[rune]int {frequency := make(map[rune]int)for _, char := range str {frequency[char] = frequency[char]+1}return frequency}func main() {var input stringfmt.Scanln(&input)frequency := countCharacters(input)fmt.Println("Character frequency:")for char, count := range frequency {fmt.Printf("%c: %d\n", char, count)}}
Enter the input below
Lines 7–8: The countCharacters
function is defined, taking a string str
as input and returning a map of type map[rune]int
. Since Go does not have a specific data type for characters, it uses the rune
type to represent character values. The function initializes an empty map named frequency
to store the frequencies of each character.
Lines 9–14: The for
loop iterates over each character (char
) in the str
string. Inside the loop, the code increments the count of char
in the frequency
map by one.The frequency
map is returned once the loop is complete.
Lines 21–23: The for
loop iterates over the frequency
map using range
. In each iteration, it retrieves the character (char
) and its corresponding frequency (count
).
The time complexity depends on the length of the input string, denoted as n
. The countCharacters
function iterates over each character in the input string str
using a for loop. This loop has a complexity of
Therefore, the overall time complexity of the countCharacters
function is
Free Resources