go: add «3043. Find the Length of the Longest Common Prefix»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-09-24 23:11:59 +02:00
parent 5d40a9cbd4
commit 60cb9ae2e3
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,42 @@
package main
import "strconv"
type LCPTrieNode struct {
children [10]*LCPTrieNode
has [2]bool
}
func longestCommonPrefix(arr1 []int, arr2 []int) int {
update := func(node *LCPTrieNode, number string, index int) int {
best := 0
for i := range number {
child := number[i] - '0'
if node.children[child] == nil {
node.children[child] = &LCPTrieNode{}
}
node = node.children[child]
node.has[index] = true
if node.has[index] && node.has[(index+1)%2] {
best = i + 1
}
}
return best
}
root := LCPTrieNode{}
for _, num := range arr1 {
strnum := strconv.Itoa(num)
update(&root, strnum, 0)
}
longest := 0
for _, num := range arr2 {
strnum := strconv.Itoa(num)
longest = max(longest, update(&root, strnum, 1))
}
return longest
}