Skip to content

Instantly share code, notes, and snippets.

@yagihiro
Created February 12, 2010 02:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yagihiro/302245 to your computer and use it in GitHub Desktop.
Save yagihiro/302245 to your computer and use it in GitHub Desktop.
suffix array sample by ruby
require "bsearch" # http://0xcc.net/ruby-bsearch/index.html.en
class SuffixArray
attr_accessor :word # original string(String)
attr_accessor :sary # suffix array(Array)
def initialize word
@word = word
@sary = Array.new(@word.size) {|i| i }
@sary.sort! {|i, j| @word[i..-1] <=> @word[j..-1] }
end
def search key
i = @sary.bsearch_first {|x| @word[x, key.size] <=> key }
@word[@sary[i], key.size]
end
end
sary = SuffixArray.new 'abracadabra'
p sary
p sary.search('ra')
sary = SuffixArray.new 'mississippi'
p sary
p sary.search('ppi')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment