go: add «3043. Find the Length of the Longest Common Prefix»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
5d40a9cbd4
commit
60cb9ae2e3
1 changed files with 42 additions and 0 deletions
42
go/find-the-length-of-the-longest-common-prefix.go
Normal file
42
go/find-the-length-of-the-longest-common-prefix.go
Normal 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
|
||||
}
|
Loading…
Reference in a new issue