Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. ##
  2. ## Find the substring in a string.
  3. ##
  4. def find_sub(str, subs)
  5. ## This algorithm runs in O(n) time,
  6. ## where n is the length of the string.
  7. ##
  8. ## Breaking it (for the worst case):
  9. ## First loop runs for n/m, second loop for n/m*(3m)
  10. ## which makes it: 2*n/m*3m => 6n => n
  11.  
  12. r = -1
  13.  
  14. ## Part the string in lengths equal to length of the substring (the last part will be equal/smaller)
  15. i = 0
  16. j = subs.length-1
  17. parts = []
  18. while true
  19. parts << [str[i..j], i] unless str[i..j].empty?
  20. break if str[i..j].length < subs.length
  21. i = j+1
  22. j += subs.length
  23. end
  24. p parts
  25.  
  26. pref = ""
  27. parts.each do |part|
  28. if part[0] == subs
  29. ## found it!
  30. r = part[1]
  31. break
  32. end
  33.  
  34. if pref.length > 0
  35. ## found prefix, match suffix
  36. prefl = pref.length
  37. for i in 0..part[0].length-1
  38. c = part[0][i]
  39. if subs[i+prefl] == c
  40. pref.concat(c)
  41. end
  42. end
  43. break if subs == pref
  44. if prefl == pref.length
  45. pref = ""
  46. r = -1
  47. ## find prefix, in this part
  48. res = find_prefix(subs, part[0], part[1], pref, r)
  49. pref, r = res[0], res[1]
  50. end
  51. else
  52. ## find prefix
  53. res = find_prefix(subs, part[0], part[1], pref, r)
  54. pref, r = res[0], res[1]
  55. end
  56. end
  57. r
  58. end
  59.  
  60. def find_prefix(subs, pa0, pa1, pref, r)
  61. j = 0
  62. for i in 0..pa0.length-1
  63. c = pa0[i]
  64. if subs[j] == c
  65. r = i+pa1 if r == -1
  66. pref.concat(c)
  67. j += 1
  68. elsif subs[j-1] == c
  69. ## to ignore concurrent same characters
  70. r += 1 if r != -1
  71. next
  72. else
  73. pref = ""
  74. j = 0
  75. r = -1
  76. end
  77. end
  78. return [pref, r]
  79. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement