Java Program to Check Whether a String/Number is a Palindrome
A palindrome string in Java is a number, word, phrase, or another sequence of characters that reads the same forwards and backward. This article focuses on determining whether a given word or number is a palindrome or not.
Palindrome Example
The string "abcba" is a palindrome, while the string "abca" is not.
In the image given below, there is a sequence of digits that make it a palindrome number-
Methods to Check Palindrome String in Java
There are three main methods to check palindrome string in Java. They are listed below:
- Naive Method
- Two Pointer Method
- Recursive Method
Naive Method to Check Palindrome String in Java
In this approach, we check whether the palindrome string is in Java by reversing it and comparing it with the original string. Let's see the below example to understand clearly:
Output:
Time Complexity: O(N)
N is the length of the input string, as the for loop iterates through each character once to create the reverse string.
Space Complexity: O(N)
Because the reverse string is stored in a separate variable proportional to the length of the input string.
Two Pointer Method for String Palindrome Program in Java
In this approach, we utilize two pointers, i and j, where i points to the start of the string and j points to the end. We compare the characters at these positions by incrementing i and decrementing j. If they match, we continue; otherwise, we conclude that the string is not a palindrome.
Output:
Time Complexity- O(n)
Space Complexity- O(1)
Recursive Method to Check String Palindrome in Java
We adopt a recursive approach similar to the two-pointer technique to determine if a palindrome string in Java. Two pointers, 'i' and 'j', initially point to the start and end of the string, respectively.
We compare the characters at positions 'i' and 'j' during each recursive call. If they match, we move 'i' one step forward and 'j' one step backwards and make a recursive call with the updated indices.
This process continues until 'i' becomes greater than or equal to 'j'. If, at any point, the characters at 'i' and 'j' don't match, we immediately return false, indicating that the given string is not a palindrome.
If every character pairs match until 'i' becomes greater than or equal to 'j', we conclude that the string is a palindrome and return true.
Output:
Time Complexity- O(n)
Space Complexity- O(n)
Conclusion
- A palindrome is a word, number, phrase, or a general sequence that reads the same backwards as forwards.
- We can determine whether a string is a palindrome by reversing and comparing it with the given original string.
- One slightly optimized approach is to compare the values at indices equidistant from both ends.
- We can determine a palindromic number by reversing it and comparing it with the original number.