In this tutorial we will write different solutions for palindrome string in java. In is one of the questions asked in interviews.
What is a palindrome?
A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction. Here is an example of palindrome string.
Write a program to check palindrome string in java
/** * * @author programtalk.com * */ public class CheckPalindrome { boolean isPalindrome(String input) { int stringLength = input.length(); int indexLastElement = stringLength -1; for (int i = 0; i < stringLength / 2; i++) { if (input.charAt(i) != input.charAt(indexLastElement - i)) { return false; } } return true; } public static void main(String[] args) { CheckPalindrome checkPalindrom = new CheckPalindrome(); System.out.println("madam is plaindrome : " +checkPalindrom.isPalindrome("madam")); System.out.println("running is palindrome : "+checkPalindrom.isPalindrome("running")); } }
Output
madam is plaindrome : true running is palindrome : false
Check Palindrome using StringBuilder.reverse()
/** * * @author programtalk.com * */ public class CheckPalindrome { boolean isPalindrome(String input) { return input.equals(new StringBuilder(input).reverse().toString()); } public static void main(String[] args) { CheckPalindrome checkPalindrom = new CheckPalindrome(); System.out.println("madam is plaindrome : " + checkPalindrom.isPalindrome("madam")); System.out.println("running is palindrome : " + checkPalindrom.isPalindrome("running")); } }
StringBuilder().reverse() reverses the String and then checking for equality does the palindrom check. But this solution is not very efficient, for more see here
Note : Instances of StringBuilder
are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer
be used.
You may also be interested in: