Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Palindrom searcher class
class PalindromSearcher
attr_accessor :string
def initialize(string)
@string = string
end
def longest
return unless all.any?
all.max_by(&:length)
end
def all
words & reverse_words
end
private
def words
substrings(string)
end
def reverse_words
substrings(string.reverse)
end
def substrings(string)
return if string.nil?
return if string.empty?
substrings = []
for first_char in 1..(string.length - 1)
for last_char in (first_char + 1)..string.length
substrings << string[(first_char - 1)..(last_char - 1)]
end
end
substrings
end
end
puts PalindromSearcher.new('xyzzy').longest # yzzy
puts PalindromSearcher.new('afbbbfjdjklgdfdhfdkjfffhhfffjkdfhdhkyejejfjkd').longest # dhfdkjfffhhfffjkdfhd
puts PalindromSearcher.new('bartarcarracecarbartar').longest # racecar
puts PalindromSearcher.new('1415926535897932384626433832795028841971').longest # 46264
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.