Skip to main content

Solution 4: Palindrome

A palindrome is a series of characters which is the same spelled forward and in reverse. For the purpose of this exercise, a capital letter is equal to its lowercase equivalent. Given a string, return whether or not the string is a palindrome. Return true if it is, and false if it is not.

def is_palindrome(string)
string = string.downcase
first = 0
last = string.length - 1

loop do
break if first == last || first > last
return false if string[first] != string[last]
first = first + 1
last = last - 1
end

true
end

Author's Note:

Ruby's core library provides a String method which makes this algorithm simpler than one may initially believe. This one-line solution appears again in the solution for Almost Palindrome.

def is_palindrome(string)
string == string.reverse
end