Check if string is a palindrome
11 March 2022 (Updated 23 May 2022)
On this page
TLDR
You want a function that takes a string and returns true
if it’s a palindrome or false
if it’s not. Something like this:
is_palindrome?('john') // false
is_palindrome?('anna') // true
Here’s how in Ruby:
def is_palindrome?(str)
reversed_str = str.split('').reverse.join
reversed_str == str
end
Explanation
There are two steps:
- Reverse string.
- Check if reversed string is the same as original string.
Tagged:
Algorithms