In first step we take a sting and its length. We traverse the sting on both the side simultaneously, like 1st character of the sting is compared with last character of the sting so if that matches then continue the loop Otherwise just break the loop, come out of the loop and print the respective message. Here are the some palindrome strings examples: "madam", "dad" etc..
Here you can find two versions of program where first one is same which explained earlier and second version is of reverse pattern. The reverse version starts with getting the length of the string as int end=st1.length()-1; . The for is trick here we starts from the end to beginning and check the character.
Version : 1
import java.util.*; import java.lang.*; class PalindromeProgram { public static void main(String args[]) { String st1="aba"; int end=st1.length()-1; int flag=0; for (int j=0;j<=end;j++) { if (st1.charAt(j)!=st1.charAt(st1.length()-j-1)) { flag=1; break; } } if(flag==1) System.out.printf("'%s' string is not a palindrome",st1); else System.out.printf("yes,'%s' string is palindrome",st1); } }
Version : 2
import java.util.*; import java.lang.*; class ReverseVersion { public static void main(String args[]) { String st1="aba"; int end=st1.length()-1; int flag=0; String copy=""; for (int j=end;j>=0;j--) { copy=copy+st1.charAt(j); } System.out.printf("\nOriginal string : %s",st1); System.out.printf("\nReversed string : %s\n",copy); if(st1.equals(copy)) System.out.printf("yes,'%s' string is palindrome",st1); else System.out.printf("'%s' string is not a palindrome",st1); } }
No comments:
Write comments