Algorithm Approach : Palindrome
Eric Saldivar
Posted on May 22, 2021
Welcome to my first post in a series of post I hope to make once a week or at least once every other week. I want to approach popular algorithms and explain my approach to solving them. I hope you find this helpful, feel free to reply/comment about anything I did right, wrong, or what you may have done differently.
So let's get to it! First, the prompt:
Things we know:
- The parameter is a string.
- It will contain at least one character as it will be non-empty.
- We must return either true or false. True if the string is a palindrome and false if it is not.
The approach:
Let's start with a case that we can immediately return as true. If the length of the string is 1 then we will return true as a string of 'a' for example will be 'a' as it really doesn't have a reverse order to read.
Now what do we do in the case where a string has a length greater than one?
I chose to declare a variable with the label of revStr (reversed string) which splits the string, reverses the order, and joins the string back together.
Let's break that down further.
The split method
We use this string method to separate the characters of a string and make them values in an array. We pass in a parameter of '' to split every character. If we passed in ' ' we would separate every word. Look at the MDN docs linked above to understand the split method further.
Now if we had the string racecar we would have ['r','a', 'c', 'e', 'c', 'a', 'r']
We can use this because we are going to apply array methods now!
The reverse method
We have reversed the array. No parameters, we just want all values in the array in reverse order.
The join method
This methods connects all values in an array together. If a string parameter is passed in then the characters are joined together with the string between each value. We passed in '' so we join the values with no space or characters between them as a string.
So we chained all those methods and what do we have now?
We have the original string reversed!
Ex. original string = apple, reversed string = elppa
The last thing we do is return the boolean value of checking if the original string is exactly equal to the reverse string. If they are the same we return true if not then we return false.
And that is it! Thanks for hanging in there, I will try to be concise but I want to provide links to methods and my reasoning for doing things in as clear a way as possible!
Posted on May 22, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.