node.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package stringx
  2. type node struct {
  3. children map[rune]*node
  4. fail *node
  5. depth int
  6. end bool
  7. }
  8. func (n *node) add(word string) {
  9. chars := []rune(word)
  10. if len(chars) == 0 {
  11. return
  12. }
  13. nd := n
  14. for i, char := range chars {
  15. if nd.children == nil {
  16. child := new(node)
  17. child.depth = i + 1
  18. nd.children = map[rune]*node{char: child}
  19. nd = child
  20. } else if child, ok := nd.children[char]; ok {
  21. nd = child
  22. } else {
  23. child := new(node)
  24. child.depth = i + 1
  25. nd.children[char] = child
  26. nd = child
  27. }
  28. }
  29. nd.end = true
  30. }
  31. func (n *node) build() {
  32. var nodes []*node
  33. for _, child := range n.children {
  34. child.fail = n
  35. nodes = append(nodes, child)
  36. }
  37. for len(nodes) > 0 {
  38. nd := nodes[0]
  39. nodes = nodes[1:]
  40. for key, child := range nd.children {
  41. nodes = append(nodes, child)
  42. cur := nd
  43. for cur != nil {
  44. if cur.fail == nil {
  45. child.fail = n
  46. break
  47. }
  48. if fail, ok := cur.fail.children[key]; ok {
  49. child.fail = fail
  50. break
  51. }
  52. cur = cur.fail
  53. }
  54. }
  55. }
  56. }
  57. func (n *node) find(chars []rune) []scope {
  58. var scopes []scope
  59. size := len(chars)
  60. cur := n
  61. for i := 0; i < size; i++ {
  62. child, ok := cur.children[chars[i]]
  63. if ok {
  64. cur = child
  65. } else {
  66. for cur != n {
  67. cur = cur.fail
  68. if child, ok = cur.children[chars[i]]; ok {
  69. cur = child
  70. break
  71. }
  72. }
  73. if child == nil {
  74. continue
  75. }
  76. }
  77. for child != n {
  78. if child.end {
  79. scopes = append(scopes, scope{
  80. start: i + 1 - child.depth,
  81. stop: i + 1,
  82. })
  83. }
  84. child = child.fail
  85. }
  86. }
  87. return scopes
  88. }