簡體   English   中英

為什么這段代碼在我的系統上能正常工作,並在HackersRank中拋出EmptyStackException

[英]Why this code is working fine on my system and throwing EmptyStackException in HackersRank

https://www.hackerrank.com/challenges/counting-valleys/problem中存在計數谷問題,我知道我不是最好的解決方案,但它在帶有示例測試用例的系統上可以正常工作,但似乎在hackersRank上失敗相同的測試用例。這會在“ climbStack.peek()”上引發emptyStack異常,我嘗試使用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 UDDDUDUU

結果1

我的猜測是, split()方法在J7中的工作方式不同於J9。 如果您的輸入僅是'U'和'D'字符的字符串,並且您需要將它們分成單個字母,那么我建議使用toCharArray()而不是split() ,該方法將為您提供長度為8的char[] -使用自從早期Java版本發布以來,您發布的示例輸入和toCharArray()方法toCharArray()存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM