Palindrome-ing
My approach to Palindrome
I want to approach popular algorithms and explain my approach to solving them. In saying that let's get started with the ever so popular Palindrome.
What 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.
My 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. 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 their 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 method 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 reversed string. If they are the same we return true if not then we return false.