64.9k views
2 votes
Consider an array inarr containing atleast two non-zero unique positive integers. Identify and print, outnum, the number of unique pairs that can be identified from inarr such that the two integers in the pair when concatenated, results in a palindrome. If no such pairs can be identified, print -1.Input format:Read the array inarr with the elements separated by ,Read the input from the standard input streamOutput format;Print outnum or -1 accordinglyPrint the output to the standard output stream

1 Answer

4 votes

Answer:

Program.java

import java.util.Scanner;

public class Program {

public static boolean isPalindrome(String str){

int start = 0, end = str.length()-1;

while (start < end){

if(str.charAt(start) != str.charAt(end)){

return false;

}

start++;

end--;

}

return true;

}

public static int countPalindromePairs(String[] inarr){

int count = 0;

for(int i=0; i<inarr.length; i++){

for(int j=i+1; j<inarr.length; j++){

StringBuilder sb = new StringBuilder();

sb.append(inarr[i]).append(inarr[j]);

if(isPalindrome(sb.toString())){

count++;

}

}

}

return count == 0 ? -1 : count;

}

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String line = sc.next();

String[] inarr = line.split(",");

int count = countPalindromePairs(inarr);

System.out.println("RESULT: "+count);

}

}

Step-by-step explanation:

OUTPUT:

Consider an array inarr containing atleast two non-zero unique positive integers. Identify-example-1
User Ricb
by
5.1k points