-2

ヘッズ シリーズで最も頻繁に使用される長さを特定する必要があります。最も頻繁な頭部シリーズの長さが複数ある場合は、最も長いものを出力します。トライアルに頭がない場合は、ゼロを出力します。

例 :

入力: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示す23

最も頻繁な長さが複数ある場合は、最も長いものを表示する必要があるためです。助けてください。

4

2 に答える 2

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

このコードには 2 つのループがありますが、最初のループで最も頻繁なシーケンスを更新すれば、1 つにすることができます。さらに、検討している文字列と同じ長さの配列を作成する代わりの方法を見つけたいと思うかもしれません。

于 2016-05-21T07:36:54.543 に答える
0

あなたは最初ではなくelse2 番目に関連付けられているため、カウンターが間違ったタイミングでゼロになっています。これは、関連付けをコンパイラに明確にするための中括弧が配置されていないためです。1 行のステートメントであっても、常にステートメントに中かっこを使用する習慣を身に付ける必要があります。このようなエラーを防ぎます。インデントだけに頼らないでください。構文的に重要ではありません。また、最も頻繁な長さではなく最大の長さを計算しているため、変数名も変更することは理にかなっています。iffrequentLenif

修正されたコードは次のとおりです。

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);
于 2016-05-21T07:05:43.107 に答える