Created
February 12, 2010 02:45
-
-
Save yagihiro/302245 to your computer and use it in GitHub Desktop.
suffix array sample by ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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