LeetCode/go/find-the-length-of-the-longest-common-prefix.go

43 lines
786 B
Go
Raw Normal View History

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
}