Examine if a palindromic string might be obtained by concatenating substrings cut up from identical indices of two given strings

by admin

  

import java.io.*;

import java.util.*;

  

class GFG {

  

    

    

    static boolean isPalindrome(String str)

    {

  

        

        int i = 0, j = str.size() - 1;

  

        

        whereas (i < j) {

  

            

            if (str.charAt(i)

                != str.charAt(j))

                return false;

  

            

            

            i++;

            j--;

        }

  

        

        return true;

    }

  

    

    

    static void formPalindrome(

        String a, String b, int n)

    {

        

        char aa[] = new char[n + 2];

        char bb[] = new char[n + 2];

  

        Arrays.fill(aa, ' ');

        Arrays.fill(bb, ' ');

  

        

        

        for (int i = 1; i <= n; i++) {

            aa[i] = a.charAt(i - 1);

            bb[i] = b.charAt(i - 1);

        }

  

        boolean okay = false;

  

        for (int i = 0; i <= n + 1; i++) {

  

            

            

            StringBuilder la

                = new StringBuilder();

            StringBuilder ra

                = new StringBuilder();

            StringBuilder lb

                = new StringBuilder();

            StringBuilder rb

                = new StringBuilder();

  

            for (int j = 1;

                 j <= i - 1; j++) {

  

                

                la.append((aa[j] == ' ')

                              ? ""

                              : aa[j]);

  

                

                lb.append((bb[j] == ' ')

                              ? ""

                              : bb[j]);

            }

  

            for (int j = i;

                 j <= n + 1; j++) {

  

                

                ra.append((aa[j] == ' ')

                              ? ""

                              : aa[j]);

  

                

                rb.append((bb[j] == ' ')

                              ? ""

                              : bb[j]);

            }

  

            

            

            

            if (isPalindrome(la.toString()

                             + rb.toString())

                || isPalindrome(lb.toString()

                                + ra.toString())) {

                okay = true;

                break;

            }

        }

  

        

        if (okay)

            System.out.println("Sure");

  

        

        else

            System.out.println("No");

    }

  

    

    public static void fundamental(String[] args)

    {

        String A = "bdea";

        String B = "abbb";

  

        int N = 4;

  

        formPalindrome(A, B, N);

    }

}

Related Posts

Leave a Comment