Wednesday, 6 January 2016

How to find whether the input string is rotational palindrome or not ??

package org.cmania;

public class RotationalPalindrome{

public static void main(String[] args)
{

/**
* Rotational palindrome in java
* If we rotate a string and it forms a palindrome its called rotational palindrome
* aaaad -after rotation- aaada (NRP) - again after rotation - aadaa (RP)
* NRP - Not Rational Palindrome.
* We will keep on rotating our string until our rotated string becomes equal to input string.
*/

String inputString;
                 inputString = "aaaad";
       
                 isRotationalPaliondrome(inputString);
       
  }
 
 
  /**wrapper method which calls rotateString() method, until we have checked all possible rotations          of String.
   */
 
public static boolean isRotationalPaliondrome(String inputString)
{
                char ar[]=inputString.toCharArray();
                for(int x=0;x<inputString.length();x++)
                {
                      rotateString(ar);
                      if(isPalindrome(ar))
                      {
                             System.out.println("inputString(i.e "+inputString+") is rotation of the palindrome: "+String.valueOf(ar));
                             return true;
                      }
                }
                return false;    
     }
 
  /**
   * Method rotates the String.
   */
 
public static void rotateString(char[] ar)
{
         char temp = ar[0];
         int x=0;
         for(x=0;x<ar.length-1;x++)
         {
                ar[x]=ar[x+1];
         }
         ar[x]=temp;
      }
 
  /**
   * Palindrome Check
   */
  public static boolean isPalindrome(char ar[])
  {
         for(int i=0,j=ar.length-1; i<(ar.length/2); i++,j--)
         {
             if(ar[i]!=ar[j])
                return false;
         }
    return true;
 
  }

}

No comments:

Post a Comment

JSP interview questions and answers

Q1. What is JSP and why do we need it? JSP stands for JavaServer Pages. JSP is java server side technology to create dynamic web pages. J...