Skip to content

Instantly share code, notes, and snippets.

@ready4god2513
Last active August 29, 2015 14:06
Show Gist options
  • Save ready4god2513/37800036bd7d36bef288 to your computer and use it in GitHub Desktop.
Save ready4god2513/37800036bd7d36bef288 to your computer and use it in GitHub Desktop.
Longest Palindrome Finder in Ruby
def longest_palind(s)
# First find all palindromes. The way we can do
# this is to scan through the letters searching for
# the middle. We can find the middle by detecting a letter
# that meets one of two criteria- has the same letter before and after it,
# or is the same letter. Once we have found that it is a palindrome,
# continue to expand the search finding the length. Once we have the length
# extract the string and append to the array. Sort the array by the longest
# and shift.
all_pals = pals_in_str(s)
puts all_pals.sort_by(&:length).reverse.first
end
def pals_in_str(s)
pals = []
len = s.length
letters = s.scan(/./)
letters.each_with_index do |char, index|
if char == letters.at(index + 1)
pals << build_pal(letters, char.dup.concat(letters.at(index + 1)), index, (index + 1))
elsif letters.at(index - 1) == letters.at(index + 1)
pals << build_pal(letters, char.dup, index, index)
end
end
pals
end
def build_pal(letters, data, start, stop)
steps = 0
match = true
while match
steps += 1
prev = letters.at(start - steps)
nexxt = letters.at(stop + steps)
match = false
if prev == nexxt
data.insert(0, prev)
data.insert(-1, nexxt)
match = true
end
end
data
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment