Skip to main content

Solution 6: Almost 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 would be a palindrome if one or fewer characters were removed. Return true if it is a palindrome or almost a palindrome, and false otherwise.

def palindrome(string)
return true if string == string.reverse

valid = true
one_off = false
looping = true
first = 0
last = string.length - 1

while looping
break if first > last

if string[first] == string[last]
first = first + 1
last = last - 1
looping = false if first == last || first > last
next
end

if one_off
valid = false
break
end

if string[first+1] == string[last]
one_off = true
first = first + 2
last = last - 1
looping = false if first == last
next
end

if string[first] == string[last-1]
one_off = true
first = first + 1
last = last - 2
looping = false if first == last
next
end

valid = false
break
end

valid
end