In this article, we will take a look at different ways to check for a palindrome string in java.
A palindrome string is one which is the same when reversed.
Method 1: Iterating with while loop
Initialize two counter variables, one pointing to the first character and other pointing to the last character. Now, loop till the start variable and end variable become equal, which means that all the characters are covered.
In each loop iteration, compare the character from one end with corresponding character from the other end.
If the corresponding characters match, means the string is palindrome.
Example program to check for palindrome string is given below.
String s = "madam"; // variables pointing to first and last characters int start = 0, end = s.length() - 1; boolean isPalindrome = true; // loop to cover all characters while(start < end) { // compare left and right characters if(s.charAt(start) != s.charAt(end)) { // set flag isPalindrome = false; // terminate the loop break; } start++; end--; } // check if string is palindrome if(!isPalindrome) { System.out.println("Not Palindrome"); } else { System.out.println("Palindrome"); }
Note that as the first mismatch of characters is found, the string is not palindrome and there is no need to continue the loop, so it is terminated with break statement.
Method 2: Using recursion
Above algorithm can also be written using recursion where instead of using a loop, we call the function again and again. This function receives three arguments:
A. start index that points to a character from the left, initialized to 0 at first.
B. end index that points to a character from the left, initialized to the length of string at first.
C. String to be reversed.
static boolean check(int start, int end, String s) { if(start > end) { return true; } if(s.charAt(start) != s.charAt(end)) { return false; } return check(start+1, end-1, s); }
To reverse a string, the above function should be invoked as below. Here, the first value should be 0, second should be the length of the string and third is the string to be reversed.
String s = "madam"; check(0, s.length(), s);
Method 3: Reversing string
In this method. we reverse the string and then compare it with the original string. If they both are same, the string is palindrome.
There are many ways to reverse a string in java but here, we will use java.lang.StringBuffer
.
This class has a reverse()
method which reverses the string. Use its toString()
method to convert StringBuffer
to a string. Example,
String s = "madam"; StringBuffer st = new StringBuffer(s); String rev = st.reverse().toString(); if(!rev.equals(s)) { System.out.println("Not Palindrome"); } else { System.out.println("Palindrome"); }
Method 4: Using stack
A stack is a data structure based on LIFO(Last In First Out) principle. Item that enters last will leave the stack first.
Add operation in stack is called push while retrieval is called pop. So, if characters of a string are pushed into the stack and then popped one by one, they will be in reverse order.
String s = "madam"; Stack<Character> stack = new Stack<>(); // add characters to stack for (char c : s.toCharArray()) { stack.push(c); } StringBuffer b = new StringBuffer(); // iterate over stack while(!stack.isEmpty()) { // pop characters and add to StringBuffer b.append(stack.pop().toString()); } // compare if(s.equals(b.toString())) { System.out.println("Palindrome"); } else { System.out.println("Not Palindrome"); }
Note that we are using StringBuffer to add characters popped out of stack to a string. This is because StringBuffer
is mutable and no new objects are created.
It is not recommended to add these characters directly to a string using + operator since String is immutable and each addition will create a new String object.
Further readings:
1. Reverse string with stack.
2. Check for palindrome string using stack.
Method 5: Using Queue
This approach is similar to previous one but it uses a Queue to add and remove characters.
A Queue is a FIFO(First In First Out) data structure.
This means that items are retrieved in the same order in which they were inserted. So, to add characters to a queue, we need to traverse the string in opposite direction, from last character to first character.
These characters are then retrieved one be one and appended to a StringBuffer
, which is then converted to a string.
This string and the original string are compared to check if the string is palindrome. Example,
String s = "mdadam"; Queue<Character> q = new LinkedList<>(); // iterate over the characters for (int i = s.length() - 1; i >= 0; i--) { q.add(s.charAt(i)); } StringBuffer b = new StringBuffer(); // iterate over q while (!q.isEmpty()) { // remove each character b.append(q.remove().toString()); } if (s.equals(b.toString())) { System.out.println("Palindrome"); } else { System.out.println("Not Palindrome"); }
Note that java.util.Queue
is an interface and LinkedList class implements it.
Method 6: Using character array
This method is based on following steps:
A. Create an array of characters of the same length as the length of string.
B. Iterate over the characters of the string from end to start.
C. In each iteration, add the character to the array.
D. Create a string from this character array. This string will be the reverse of the actual string.
E. Compare the string created in D with the original string.
Example program is given below.
String s = "madam"; // define a character array char[] arr = new char[s.length()]; // iterate string in reverse for (int i = s.length() - 1; i >= 0; i--) { // assign character to array arr[i] = s.charAt(i); } // create string from array String rev = new String(arr); // compare strings if (s.equals(rev)) { System.out.println("Palindrome"); } else { System.out.println("Not Palindrome"); }
Hope the article was useful.