Sunday, September 4, 2016

Program to find out shortest palindrome of given string

package shortestpalindromeexample.java;
import java.util.Scanner;

public class ShortestPalindromeDemo {

public static String shortestPalindrome(String str) {
     
int x=0;  
int y=str.length()-1;
     
  while(y>=0){
     if(str.charAt(x)==str.charAt(y)){
          x++;
         }
            y--;
  }

if(x==str.length())
return str;

String suffix = str.substring(x);
String prefix = new StringBuilder(suffix).reverse().toString();
String mid = shortestPalindrome(str.substring(0, x));

return prefix+mid+suffix;
}

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.println("Enter a String to find out shortest palindrome");

String str=in.nextLine();


System.out.println("Shortest palindrome of "+str+" is "+shortestPalindrome(str));

}


}

Output:

Enter a String to find out shortest palindrome
java
Shortest palindrome of java is avajava


Bhanu Namikaze

Author & Editor

Bhanu Namikaze is an Ethical Hacker, Passionate Blogger, Web Developer, Student and Mechanical Engineer. He Enjoys writing articles, Blogging, Solving Errors, Surfing and Social Networking. Feel Free To Contact Me @ Bhanu.

0 comments:

Post a Comment

Popular Posts

Copyrights @ Interview Questions.Me - Blogger Templates Designed by Templateism - Distributed By Protemplateslab

  • (91) 5544 654942
  • Bhanu@HackingDream.net
  • Interview Questions

Copyrights @ Interview Questions.Me -A Site By Bhanu In Association With Hacking Dream