Sunday, October 1, 2023

Converting Non-Palindrome Word Into Palindrome

 Convert the non-palindrome words of the sentence into palindrome words by concatenating the word by its reverse (excluding the last character).

Example: The reverse word of HELP would be LEH (omitting the last alphabet) and by concatenating both, the new palindrome word is HELPLEH. Thus the word HELP becomes HELPLEH.

Note: The words which end with repeated alphabets, for example ABB would become ABBA and not ABBBA and XAZZZ becomes XAZZZAX.


import java.util.*;

class Ab

{

  String str1,str2;

  Scanner sc=new Scanner(System.in);

  int c=0;

  void show()

  {

      int len,i;

      c=1;

      System.out.print("\nEnter the Word:");

      str1=sc.next();

      if(notPalin(str1))

      {

         len=str1.length();

         for(i=len-1;i>0;i--)

         {

             if(str1.charAt(i)==str1.charAt(i-1))

             c++; /* 'c' marks the index where mismatch of characters happen */

            }

         }

         str2=leftRev(str1.substring(0,str1.length()-c)); 

         str1=str1+str2;

         System.out.println("\nModified="+str1);

      }

    

    private boolean notPalin(String str1)

    {

       int i,len;

       len=str1.length()-1;

       for(i=0;i<=len;i++)

       {

           if(str1.charAt(i)!=str1.charAt(len-1))

           break;

       }

       if(i<=len)

       return true;

       else

       return false;

    }

    private String leftRev(String str1)

    {

       int i,len;

       String str2="";

       len=str1.length(); 

       for(i=len-1;i>=0;i--)

       str2=str2+str1.charAt(i);

       return str2;

    }

public static void main(String args[])

{

Ab obj=new Ab();

obj.show();

}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner