Count number of repeated characters from a String which is a palindrome and then calculate the product of those separate counts.

How will you count a number of repeated characters from a String which is a palindrome and then calculate the product of those separate counts?
For example, if the String is ababa, the output should be the product of 3 a’s and 2 b’s which is 6.

The program is implemented in Java.

Algorithm:

(1) First, check whether the String is a palindrome.

(2) Set count =1 for the character you going to compare it with the whole string and then use a character, for example, I used ‘$’ to keep counting

(3) Multiply the counts separately into a variable.

 


package HackersData;

import java.util.*;
import java.lang.*;
import java.io.*;
import java.lang.String;

class HackersData
{

public static void main (String[] args) throws java.lang.Exception
{
String str=new String();
int product=1, count=1;

Scanner scan = new Scanner(System.in);
str = scan.nextLine();
scan.close();

/* Reverse string and compare to original */
String reversed = new StringBuilder(str).reverse().toString();

StringBuilder dollar = new StringBuilder(str);

if(str.equals(reversed))
{
System.out.println("str.length():"+str.length());
for(int i = 0; i<str.length();i++)
{
if(str.charAt(i) == '$')
{
System.out.println(str.charAt(i));
System.out.println("continue");
continue;

}
else
{
for(int j=i+1; j<=str.length()-1; j++)
{
if(str.charAt(i) == str.charAt(j))
{
System.out.println("str.charAt(i):"+str.charAt(i));
count++;
System.out.println("count:"+count);
System.out.println("Before replacing str.charAt(j):"+str.charAt(j));
dollar.setCharAt(j,'$');
str=dollar.toString();
System.out.println("After replacing str.charAt(j):"+str.charAt(j));
System.out.println("str:"+str);
System.out.println("________________");
}
}

}
product=product * count;
count=1;
}

}

System.out.println("Product:"+product);
}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s