# HELPER METHODS
def trim(word)
word[1..-2]
end
def first_and_last_chars_match?(word)
word[0] == word[-1]
end
def less_than_two_chars?(word)
word.length < 2
end
# ITERATIVE SOLUTION
# UNTIL word has less than two characters
# IF first and last letters do not match
# NO, not a palindrome
# ELSE
# REMOVE first and last letters
# LOOP
# YES a palindrome
def iterative_is_palindrome?(word)
until less_than_two_chars?(word)
return false unless first_and_last_chars_match?(word)
word = trim(word)
end
return true
end
# RECURSIVE SOLUTION
# BASE CASE: Palindrome if word has less than two characters
# IF first and last letters do not match
# NO, not a palindrome
# REMOVE first and last letters and check again
def recursive_is_palindrome?(word)
return true if less_than_two_chars?(word)
return false unless first_and_last_chars_match?(word)
recursive_is_palindrome?(trim(word))
end
# Driver Code
puts iterative_is_palindrome?("civic") == true
puts iterative_is_palindrome?("dog") == false
puts recursive_is_palindrome?("civic") == true
puts recursive_is_palindrome?("dog") == false