Java Program to Check whether String is Palindrome or Not.
String is called Palindrome, if it is read same from front as well as from back.
In this post, we will see Algorithm to check whether string is palindrome or not.
Check if Number is Palindrome in Java
Java Program to check whether String is Palindrome or not.
It is very easy to check whether String is Palindrome or not.
Approach 1:
Reverse the original string and compare Reversed String with original string.
If reversed string and original string is same then String is Palindrome else not.
package javabypatel; public class PalindromeCheck { public static void main(String args[]){ System.out.println(isPalindrome("ABCBA")); } public static boolean isPalindrome(String originalString){ if(originalString == null){ return true; } String reversedString = ""; for (int i = originalString.length()-1; i >= 0; i--) { reversedString += originalString.charAt(i); } return originalString.equals(reversedString); } }Approach 2: In this approach, we will check whether String is Palindrome or not by comparing the characters of string from front and back together.
STEP: 1
Take 2 variable, pointer1 and pointer2.
pointer1 initialise to index 0 and pointer2 initialise to originalString.length()-1.
STEP 2:
Compare characters at pointer1 and pointer2, if they are not same, then they are not Palindrome and stop.
If they are same then increment pointer1, decrement pointer2.
Repeat STEP 2 til pointer1 < pointer2.
package javabypatel; public class PalindromeCheck { public static void main(String args[]){ System.out.println(isPalindrome("ABCBA")); } public static boolean isPalindrome(String originalString){ int pointer1 = originalString.length()-1; int pointer2=0; while(pointer1 > pointer2) { if(originalString.charAt(pointer1) != originalString.charAt(pointer2)) { return false; } pointer1--; pointer2++; } return true; } }
You may also like to see
Check if Number is Palindrome in Java
Given an array of integers. All numbers occur thrice except one number which occurs once. Find the number in O(n) time & constant extra space.
Count number of Bits to be flipped to convert A to B
Count number of Set Bits in Integer.
Check if number is Power of Two.
Find all subsets of a set (Power Set).
Skyline Problem in Java.
Find Minimum length Unsorted Subarray, Sorting which makes the complete array sorted
Count trailing zeros in factorial of a number
When to use SOAP over REST Web Service. Is REST better than SOAP?
Tower Of Hanoi Program in Java.
Enjoy !!!!
If you find any issue in post or face any error while implementing, Please comment.
No comments:
Post a Comment