Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
Is String A Palindrome?
You are given a string and are asked to write a method to return true if the string is a palindrome and to return false otherwise. A palindrome is a string that reads the same from front to back like alula
They are many solutions to check if a string is a palindrome. I’m going to show you three solutions. The first will use a StringBuilder and the second will use a Character Array to solve the problem. For the third solution, we will solve the problem in-place.
Solution Using StringBuilder
In this solution we:
- Create a StringBuilder on line 3.
- Reverse the StringBuilder and create a new String on line 5.
- Use the equals method to see two strings are the same on line 6.
Solution Using CharArray
In this solution we:
- Create a new character array on line 4 using the toCharArray() method.
- Loop through the array on line 6.
- Check if the two values are not the same on line 8. If the values are not the same we return false.
- Return true on line 10.
Solution In-Place
This solution is almost the same as the last one but, we use the charAt method to compare the characters. This solution is faster because it loops over the array at most once and does not use more memory.
Conclusion
You have seen different ways to check if a string is a Palindrome or not in this post. If you are asked this question in a technical interview, you will have some solutions under your belt.
Originally published at fluentjava.com on January 23, 2019.
Is String A ? was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.