我正在创建一个方法,接收一个字母数组 “H “或 “T”。我需要返回一个int,表示 “H “或 “T”(哪一个更长)的最长条纹。
Ex). streak({"H", "H", "T","H", "H", "H", "T", "T"});
輸出結果。3,因为一行有3个 “H”。
这是我目前所掌握的情况。
public int streak(String[] arr) {
int hCount = 0;
int tCount = 0;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i].equals("H") && !arr[i + 1].equals("T")) {
hCount++;
}
if (arr[i].equals("T") && !arr[i + 1].equals("H")) {
tCount++;
}
}
return Math.max(hCount, tCount);
}
它对一些测试用例有效,但对一些测试用例无效
streak(new String[]{"T", "H", "T", "H", "T", "H", "T", "H"}) (expect 1) or
streak(new String[]{"T", "T", "T", "T", "T", "T", "T", "T"}) (expect 8)
我不允许改变方法参数。
解决方案:
建议
最简单的方法是重置 second
计数器,当匹配条件为 first
柜台。
所以当 letter == "T"
递增 tCount
和复位 hCount
但当 letter == "H"
递增 hCount
和复位 tCount
,
这是最简单明了的解决方案,没有任何附加条件。你增加了一个计数器 maxLength
而这。
此外,这个解决方案可以被修改为适用于更多的字母。
编码
在你的方法中,你可以像解释的那样修改条件。
if (letter.equals("T")) {
tCount++;
hCount = 0;
} else if (letter.equals("H")) {
hCount++;
tCount = 0;
}
在每个循环结束时,你可以检查哪个计数器的值最大。
maxLength = Math.max(maxLength, Math.max(hCount, tCount));
完整的解决方案
public int streak(String[] arr) {
int maxLength = 0;
int hCount = 0;
int tCount = 0;
for (String letter : arr) {
if (letter.equals("T")) {
tCount++;
hCount = 0;
} else if (letter.equals("H")) {
hCount++;
tCount = 0;
}
maxLength = Math.max(maxLength, Math.max(hCount, tCount));
}
return maxLength;
}