• We have a Letter or a word then we need add some letters to it and need to find out shortest palindrome 
  • For example we take "S":  S will be the shortest palindrome string.
  • If we take "xyz"zyxyz will be the shortest palindrome string
  • So we need to add some characters to the given string or character and find out what will be the shortest palindrome string by using simple java program.


Java example Program to find out shortest palindrome of given string


  1. package shortestpalindromeexample.java;
  2. import java.util.Scanner;
  3.  
  4. public class ShortestPalindromeDemo {
  5.  
  6. public static String shortestPalindrome(String str) {
  7.      
  8. int x=0;  
  9. int y=str.length()-1;
  10.      
  11.   while(y>=0){
  12.      if(str.charAt(x)==str.charAt(y)){
  13.           x++;
  14.          }
  15.             y--;
  16.   }
  17.  
  18. if(x==str.length())
  19. return str;
  20.  
  21. String suffix = str.substring(x);
  22. String prefix = new StringBuilder(suffix).reverse().toString();
  23. String mid = shortestPalindrome(str.substring(0, x));
  24.  
  25. return prefix+mid+suffix;
  26. }
  27.  
  28. public static void main(String[] args) {
  29.  
  30. Scanner in = new Scanner(System.in);
  31.  
  32. System.out.println("Enter a String to find out shortest palindrome");
  33.  
  34. String str=in.nextLine();
  35.  
  36. System.out.println("Shortest palindrome of "+str+" is "+shortestPalindrome(str));
  37.  
  38. }
  39.  
  40. }
Output:

  1. Enter a String to find out shortest palindrome
  2. java
  3. Shortest palindrome of java is avajava

Shotest+palindrome

Instance Of Java

We are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
Java Interview programming questions on this keyword
»
Previous
Validate email address using javascript

No comments

Leave a Reply

Select Menu