在hackerrank java堆栈问题中,我已经设计了代码,但是它没有给出正确的输出,并且在测试用例中给出了运行时错误
import java.util.*;
class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input = sc.next();
System.out.println(isBalanced(sc.next()));
}
sc.close();
}
static boolean isBalanced(String parantheses) {
Stack < Character > stack = new Stack < Character > ();
for (int i = 0; i < parantheses.length(); i++) {
char ch = parantheses.charAt(i);
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
} else if (stack.empty()) {
return false;
} else {
char top = stack.pop();
if ((top == '(' && ch != ')') || (top == '[' && ch != ']') || (top == '{' && ch != '}')) {
return false;
}
}
}
return stack.empty();
}
}