如何在硬币折腾中找到最常见的头部长度?

时间:2016-05-20 18:25:39

标签: java coin-flipping

我需要找出头系列最常用的长度。如果有多个最常见的磁头系列长度,则打印时间最长。如果试验中没有头,则打印零。

  

示例:

     

输入:HTTHH

     

输出:2

     

输入: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);

当我运行此代码时,某些输入的输出不同。 例如:当我提供HHTTHHTTHHHTHHH时,它显示2但根据分配,它应显示3

因为如果有多个最常见的长度,它应该显示最长。请帮忙。

2 个答案:

答案 0 :(得分:0)

您的else与第二个if而不是第一个frequentLen相关联,因此您的if计数器在错误的时间被清零。这是因为您没有花括号来使编译器清楚地关联。您应该养成一直使用花括号进行BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); char[] c = str.toCharArray(); int currentLen = 0; int maxLen = 0; for (int i = 0; i < str.length(); i++) { if (c[i] == 'H') { currentLen++; if (currentLen > maxLen) { maxLen = currentLen; } } else { currentLen = 0; } } System.out.println(maxLen); 语句的习惯,即使对于单行语句也是如此。他们会防止像这样的错误。不要仅仅依赖于缩进 - 它在语法上并不重要。此外,在计算最大长度而不是最常用长度时,更改变量名称也是有意义的。

更正的代码是:

["aabbaacc", "bbaacc", "aacceeeeaa" "cceeeeaa"]. 

答案 1 :(得分:0)

让事情变得清晰起来。序列的最常见长度是出现最多时间的长度。所以,不知何故,你必须跟踪已经出现的每个长度的序列数。这是执行此操作的代码。

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);
}

现在,这段代码中有两个循环,但是如果我们在第一个循环中更新最频繁的序列,我们可以将它组合成一个循环。另外,您可能希望找到一种替代方法来创建与您正在考虑的字符串长度相同的数组。