Skip to content

Instantly share code, notes, and snippets.

@mgamba
Last active August 29, 2015 13:57
Show Gist options
  • Save mgamba/9719127 to your computer and use it in GitHub Desktop.
Save mgamba/9719127 to your computer and use it in GitHub Desktop.
recursive version of beautiful string finder
#s = "ABCDEFABDC".split("")
s = "nlhthgrfdnnlprjtecpdrthigjoqdejsfkasoctjijaoebqlrgaiakfsbljmpibkidjsrtkgrdnqsknbarpabgokbsrfhmeklrle".split("")
ans = 'tsocrpkijgdqnbafhmle'
#s = "CABDBACBAB".split("")
#ans = "DCBA"
h = {}.tap do |h|
s.each_with_index do |c,i|
h[c] ||= []
h[c] << i
end
end
def find_mbs(h, left_bound=-1)
return "" unless h.any?
right_bound = h.map do |char, positions|
positions.select{|p| p >= left_bound}.max
end.min
candidates = left_bound.upto(right_bound).map(&:to_i)
next_char = h.select do |char, positions|
(positions & candidates).any?
end.map(&:first).flatten.max
left_bound = h[next_char].select{|i|i> left_bound && i<=right_bound}.min
h.delete(next_char)
return "#{next_char}#{find_mbs(h,left_bound)}"
end
most_beautiful_string = find_mbs(h)
puts most_beautiful_string
puts most_beautiful_string == ans
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment