I need to find out which is the most frequent length for heads series. If there are more than one most frequent heads series lengths, print the longest. If there are no heads in the trial, print zero.
Example :
Input : HTTHH
Output : 2
Input : HTTHHHTTHHH
EDIT : Sorry I forgot to include the Code.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
char[] c = str.toCharArray();
int currentLen = 0;
int frequentLen = 0;
for (int i = 0; i < str.length(); i++)
{
if (c[i] == 'H')
{
currentLen++;
if (currentLen > frequentLen)
{
frequentLen = currentLen;
}
}
else
{
currentLen = 0;
}
}
System.out.println(frequentLen);
When I run this code, the output is different for some of the inputs.
For example: When I give HHTTHHTTHHHTHHH
it shows 2
But according to the assignment it should display 3
.
Because if there are more than one most frequent length it should display the longest. Please help.
Let's clear things up. The most frequent length of a sequence is the length that appears the most time. So somehow, you have to keep track of the number of sequences of each length that have already appeared. Here is the code to do that.
public static void freq() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
// Count the number of times each sequence appeared. The array is indexed by the length of a sequence
int[] counts = new int[str.length()];
int current = 0;
for (char value : str.toCharArray()) {
if (value == 'H') {
current++;
} else if (current != 0){
counts[current]++;
current = 0;
}
}
// If we end with 'H', increment the count
if (current != 0) { counts[current]++; }
// From the computed counts, find the one that appears the most often
int mostFrequentLength = 0;
int mostFrequentValue = 0;
for (int i = 1; i < counts.length; i++) {
if (counts[i] >= mostFrequentValue) {
mostFrequentValue = counts[i];
mostFrequentLength = i;
}
}
System.out.println(mostFrequentLength);
}
Now, there are two loops in this code, but we can make it in one if we update the most frequent sequence in the first loop. Plus, you may want to find an alternative to creating an array of the same length as the string you are considering.