Java Program To Find all Palindromic Substrings in a String


Given a String, We have to find all the palindromic sub-strings from the given string.

Example:-

Input_String =”helloworld”

Output:-[ll, r, d, e, owo, w, h, l, o]

 


Java Program to find all palindromic substrings of a given string

 

import java.util.HashSet;
import java.util.Set;

class Main
{
  // check in both directions to find all palindromes
  public static void checkPalindromes(String Input_string, int first, int last, Set<String> set)
  {
    
    while (first >= 0 && last < Input_string.length()
        && Input_string.charAt(first) == Input_string.charAt(last))
    {
      
      set.add(Input_string.substring(first, last + 1));

      first--;
      last++;
    }
  }

  //  find all unique palindrome substrings of given string

  public static void findallPalindromeSubStrings(String Input_string)
  {
    // creating one empty set to store all unique palindrome substrings

    Set<String> set = new HashSet<>();

    for (int j = 0; j < Input_string.length(); j++)
    {
      
      checkPalindromes(Input_string, j, j, set);

    
      checkPalindromes(Input_string, j, j + 1, set);
    }

    // print all unique palindrome substrings

    System.out.print(set);
  }

  public static void main(String[] args)
  {
    String Input_string = "helloworld";

    findallPalindromeSubStrings(Input_string);
  }
}

 

Output:-
[ll, r, d, e, owo, w, h, l, o]

 


 

Leave a Reply

Your email address will not be published. Required fields are marked *