Skip to content

Instantly share code, notes, and snippets.

@kballenegger
Created August 8, 2013 21:31
Show Gist options
  • Select an option

  • Save kballenegger/6188957 to your computer and use it in GitHub Desktop.

Select an option

Save kballenegger/6188957 to your computer and use it in GitHub Desktop.
An algorithm to find all / the largest palindrome in a string.
string = '111sjhfb1234321asdjkhbfhhjjhhkik'
long_palindromes = []
(0..string.length-1).each do |i|
# xyx
xyx0 = i < 1 ? nil : string[i-1]
xyx1 = string[i]
xyx2 = string[i+1]
# xx
xx0 = string[i]
xx1 = string[i+1]
[:xyx, :xx].each do |m|
case m
when :xyx
next unless xyx0 && xyx2 # if we're out of bounds
next unless xyx0 == xyx2
# palindrome :)
matched = 1
(2..1/0.0).each do |j|
b = i-j < 0 ? nil : string[i-j]
a = string[i+j]
break if a.nil? || b.nil?
break unless a == b
matched = j
end
long_palindromes << string[i-matched..i+matched]
when :xx
next unless xx1 # if we're out of bounds
next unless xx0 == xx1
# palindrome :)
matched = 1
(2..1/0.0).each do |j|
b = i-j < 0 ? nil : string[i-j]
a = string[i+j-1]
break if a.nil? || b.nil?
break unless a == b
matched = j
end
long_palindromes << string[i-matched..i+matched-1]
end
end
end
longest = long_palindromes.sort {|a,b| a.length <=> b.length }.last
p long_palindromes, longest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment