为什么此代码在hackerrank上显示运行时错误

时间:2017-02-09 13:47:02

标签: java data-structures stack operators brackets

这里给出了问题 - https://www.hackerrank.com/challenges/balanced-brackets?h_r=next-challenge&h_v=zen。以下代码显示提交时的运行时错误,我无法弄清楚出了什么问题。

import java.util.Scanner;
public class Solution {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t = in.nextInt();
    for(int a0 = 0; a0 < t; a0++){
        Stack stack=new Stack();
        int j=0;
        String s = in.next();
        for(int i=0;i<s.length();i++){
        if(s.charAt(i)=='('){
            stack.push(s.charAt(i));
        }
        else  if(s.charAt(i)=='['){
            stack.push(s.charAt(i));
        }
        else  if(s.charAt(i)=='{'){
            stack.push(s.charAt(i));
        }    
        else if(s.charAt(i)==')'){
            char str=stack.pop();
            if(str=='(')continue;
            else j=1;
        }
        else if(s.charAt(i)==']'){
            char str=stack.pop();
            if(str=='[')continue;
            else j=1;
        }
        else if(s.charAt(i)=='}'){
            char str=stack.pop();
            if(str=='{')continue;
            else j=1;
        }

        }
        if(stack.isEmpty()==false)System.out.println("NO");
        else if(j==1)System.out.println("NO");
        else if(j==0)System.out.println("YES");    
    }
}
private static class Stack{
    Node first;
    private class Node{
        char data;
        Node next;
    }
    public boolean isEmpty(){
        return (first==null);
    }
    public void push(char x){
        Node old=first;
        first=new Node();
        first.data=x;
        first.next=old;
    }
    public char pop(){
        char ch=first.data;
        first=first.next;
        return ch;
    }
    public int peek(){
        return first.data;
    }

  }
}

0 个答案:

没有答案