Report abuse


			
haystack = "yargle bargle margle hoooo missi"
needle = "mississippi"
suffixes = {}
0.upto(needle.length-2) do |i|
  needle.length.downto(1) do |j|
    suffixes[needle.slice(i,j)] = i
  end
end

hpos = haystack.length - 1
fragment_index = nil
loop do
  fragment = haystack[hpos, haystack.length]
  puts "fragment to test: #{fragment.inspect}"
  hash_index = suffixes[fragment]
  fragment_index = hash_index ? fragment.length : nil
  # break if we got to the beginning of the needle, or if the haystack no longer matches the needle fragment.
  break if hash_index.zero? || fragment_index.nil?
  puts "fragment index: #{fragment_index}"
  hpos -= 1
end

puts "final fragment index: #{fragment_index.inspect}"

# fragment_index is nil if the end of the string is not a fragment of the needle.
# If it is non-nil, it is the length of the fragment that the next chunk should be aware of.