mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
go: add «1002. Find Common Characters»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
bdc7307c3e
commit
9249f94a04
1 changed files with 34 additions and 0 deletions
34
go/find-common-characters.go
Normal file
34
go/find-common-characters.go
Normal file
|
@ -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
|
||||
}
|
Loading…
Reference in a new issue