What is a Palindrome?
A palindrome is a Number/String that is the same after reverse.
Example 1: 5445,6556,455554.
Example 2: mom, repaper, tenet.
Write a program to check the given string palindrome or not?
Solution 1: By using StringBuffer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
public class PalindromeSolution1{ public static void isPalindrome(String paliString) { /* Here we are reversing string by using StringBuffer API and setting in to another string.*/ String reversepaliString = new StringBuffer(paliString).reverse().toString(); /* * Here we are checking both strings equals or not if it's equals * given string is a Palindrome or else not a Palindrome. * */ if (paliString.equals(reversepaliString)) { System.out.println(paliString + " is Palindrome"); } else { System.out.println(paliString + " is not Palindrome"); } } public static void main(String[] args){ isPalindrome("mom"); isPalindrome("repaper"); isPalindrome("clarifyall"); } } |
mom is Palindrome
repaper is Palindrome
Solution 2: By using for loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
public class PalindromeSolution2{ public static void isPalindrome(String paliString) { String reverseString = ""; /* * Here we are reversing given string and setting in to anther string * */ for (int i=paliString.length()-1;i>=0;i--) { reverseString = reverseString + paliString.charAt(i); } /* * Here we are checked given string and reversed string same or not * if same given string is palindrome else given string not palondrome. */ if (paliString.equalsIgnoreCase(reverseString)) { System.out.println(paliString+" is palindrome."); } else { System.out.println(paliString+" is not palindrome."); } } public static void main(String[] args){ isPalindrome("tenet"); isPalindrome("repaper"); isPalindrome("java"); } } |
Output:
tenet is
java is not