Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. local concat = table.concat
  2. local tree = {}
  3.  
  4. local function tree_add(str)
  5. local p = tree
  6. for i = 1, #str do
  7. local c = str:byte(i)
  8. local n = p[c]
  9. if not n then
  10. n = {}
  11. p[c] = n
  12. end
  13. p = n
  14. end
  15. p.isleaf = true
  16. end
  17.  
  18. local function tree_route(str, i)
  19. local p = tree
  20. local greedy = -1
  21. while i <= #str do
  22. local c = str:byte(i)
  23. p = p[c]
  24. if not p then
  25. break
  26. elseif p.isleaf then
  27. greedy = i
  28. end
  29. i = i + 1
  30. end
  31. return greedy
  32. end
  33.  
  34. local function tree_match(str, func)
  35. local buf
  36. local i = 1
  37. local last = 1
  38. while i <= #str do
  39. local start = i
  40. i = tree_route(str, i)
  41. if i >= start then
  42. if not buf then
  43. buf = {}
  44. end
  45. print("sub:", str:sub(last, start - 1))
  46. buf[#buf + 1] = str:sub(last, start - 1)
  47. buf[#buf + 1] = func(str, start, i)
  48. last = i + 1
  49. else
  50. i = start
  51. end
  52. i = i+1
  53. end
  54. if buf then
  55. buf[#buf + 1] = str:sub(last)
  56. return concat(buf)
  57. else
  58. return str
  59. end
  60. end
  61.  
  62. local function tree_detect(str, ban)
  63. local i = 1
  64. local count = 0
  65. while i <= #str do
  66. local start = i
  67. i = tree_route(str, i)
  68. if i >= start then
  69. count = count + 1
  70. ban[start] = i
  71. else
  72. i = start
  73. end
  74. i = i+1
  75. end
  76. return count
  77. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement