From 9249f94a04147c1f79a872054791e866de5ddd57 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 5 Jun 2024 09:44:29 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB1002.=20Find=20Common=20Chara?= =?UTF-8?q?cters=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- go/find-common-characters.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 go/find-common-characters.go diff --git a/go/find-common-characters.go b/go/find-common-characters.go new file mode 100644 index 0000000..1c0ec7b --- /dev/null +++ b/go/find-common-characters.go @@ -0,0 +1,34 @@ +package find_common_characters + +func commonChars(words []string) []string { + A := int('a') + countCharacters := func(counters []int, word string) { + for _, c := range word { + counters[int(c)-A]++ + } + } + setCommon := func(common []int, word []int) { + for i, count := range word { + common[i] = min(common[i], count) + } + } + + commonCounters := make([]int, 26) + countCharacters(commonCounters, words[0]) + + for _, word := range words { + wordCounters := make([]int, 26) + + countCharacters(wordCounters, word) + setCommon(commonCounters, wordCounters) + } + + var result []string + for i, count := range commonCounters { + for count > 0 { + result = append(result, string(rune(A+i))) + count-- + } + } + return result +}