mirror of
https://github.com/geektutu/7days-golang.git
synced 2024-04-21 12:32:11 +00:00
81 lines
1.4 KiB
Go
81 lines
1.4 KiB
Go
package gee
|
|
|
|
import (
|
|
"fmt"
|
|
)
|
|
|
|
type node struct {
|
|
pattern string
|
|
part string
|
|
children []*node
|
|
isWild bool
|
|
}
|
|
|
|
func (n *node) String() string {
|
|
return fmt.Sprintf("node{pattern=%s, part=%s, isWild=%t}", n.pattern, n.part, n.isWild)
|
|
}
|
|
|
|
func (n *node) insert(pattern string, parts []string, height int) {
|
|
if len(parts) == height {
|
|
n.pattern = pattern
|
|
return
|
|
}
|
|
|
|
part := parts[height]
|
|
child := n.matchChild(part)
|
|
if child == nil {
|
|
child = &node{part: part, isWild: part[0] == ':'}
|
|
n.children = append(n.children, child)
|
|
}
|
|
child.insert(pattern, parts, height+1)
|
|
}
|
|
|
|
func (n *node) search(parts []string, height int) *node {
|
|
if len(parts) == height {
|
|
if n.pattern == "" {
|
|
return nil
|
|
}
|
|
return n
|
|
}
|
|
|
|
part := parts[height]
|
|
children := n.matchChildren(part)
|
|
|
|
for _, child := range children {
|
|
result := child.search(parts, height+1)
|
|
if result != nil {
|
|
return result
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (n *node) travel(list *([]*node)) {
|
|
if n.pattern != "" {
|
|
*list = append(*list, n)
|
|
}
|
|
for _, child := range n.children {
|
|
child.travel(list)
|
|
}
|
|
}
|
|
|
|
func (n *node) matchChild(part string) *node {
|
|
for _, child := range n.children {
|
|
if child.part == part || child.isWild {
|
|
return child
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (n *node) matchChildren(part string) []*node {
|
|
nodes := make([]*node, 0)
|
|
for _, child := range n.children {
|
|
if child.part == part || child.isWild {
|
|
nodes = append(nodes, child)
|
|
}
|
|
}
|
|
return nodes
|
|
}
|