gpt4 book ai didi

java - 为什么这段代码在我的系统上运行良好并在 HackerRank 中抛出 EmptyStackException

转载 作者:行者123 更新时间:2023-12-02 10:15:55 24 4
gpt4 key购买 nike

https://www.hackerrank.com/challenges/counting-valleys/problem存在计数谷问题我知道我的不是最好的解决方案,但它在我的系统上使用示例测试用例运行良好,但在具有相同测试用例的 hackersRank 上似乎失败。这会在“climbStack.peek()”上抛出空堆栈异常我用 J9 编译器尝试了以下代码,但 J7 风格,因为 hackerrank 仅支持 j7

// Complete the countingValleys function below.
static int countingValleys(int n, String s)
{
Stack<String> climbStack = new Stack<String>();
boolean mClimb = false;
int valleyCount=0;
String[] trek = s.split("");

for(int i =0 ; i < trek.length; i++)
{
if(climbStack.empty() && trek[i].equals("U"))
{
mClimb = true;
climbStack.push(trek[i]);
continue;
}
else if(climbStack.empty() && trek[i].equals("D"))
{
mClimb = false;
climbStack.push(trek[i]);
continue;
}

if(climbStack.peek().equals(trek[i]))
{
climbStack.push(trek[i]);
}
else
{
climbStack.pop();
if(climbStack.empty() && mClimb == false && i <= n)
{
valleyCount++;
}
}

}
return valleyCount;

}

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException {
//BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

String s = scanner.nextLine();

int result = countingValleys(n, s);

System.out.println(result);

scanner.close();
}

输入8嘟嘟嘟U

结果1

最佳答案

我的猜测是方法 split() 在 J7 中的工作方式与 J9 中不同。如果您的输入仅为“U”和“D”字符的字符串,并且需要将它们分成单独的字母,那么我建议使用方法 toCharArray() 而不是 split() 这将为您提供长度为 8 的 char[] - 使用您发布的示例输入,并且自早期 Java 版本以来就存在方法 toCharArray()

关于java - 为什么这段代码在我的系统上运行良好并在 HackerRank 中抛出 EmptyStackException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54685452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com