【发布时间】:2018-01-13 21:52:32
【问题描述】:
我在hackerrank中尝试平衡括号problem。
对于同一个测试用例,我得到不同的输出,这很奇怪!
这是子测试用例:
()[{}()]([[][]()[[]]]{()})([]()){[]{}}{{}}{}(){([[{}([]{})]])}
如果我单独运行,我会得到正确的答案(在我的情况下,输出是 "YES")
当这个测试用例与其他测试用例一起运行时,我得到"NO" 作为输出。
这是我为 5 个 hackos 购买的实际测试用例:
21
()[{}()]([[][]()[[]]]{()})([]()){[]{}}{{}}{}(){([[{}([]{})]])}
{][({(}]][[[{}]][[[())}[)(]([[[)][[))[}[]][()}))](]){}}})}[{]{}{((}]}{{)[{[){{)[]]}))]()]})))[
[)](][[([]))[)
]}]){[{{){
{[(}{)]]){(}}(][{{)]{[(((}{}{)}[({[}[}((}{()}[]})]}]]))((]][[{{}[(}})[){()}}{(}{{({{}[[]})]{((]{[){[
()}}[(}])][{]{()([}[}{}[{[]{]](]][[))(()[}(}{[{}[[]([{](]{}{[){()[{[{}}{[{()(()({}([[}[}[{(]})
){[])[](){[)}[)]}]]){](]()]({{)(]])(]{(}(}{)}])){[{}((){[({(()[[}](]})]}({)}{)]{{{
[(})])}{}}]{({[]]]))]})]
[{
{}([{()[]{{}}}])({})
{({}{[({({})([[]])}({}))({})]})}
()[]
{)[])}]){){]}[(({[)[{{[((]{()[]}][([(]}{](])()(}{(]}{})[)))[](){({)][}()((
[][(([{}])){}]{}[()]{([[{[()]({}[])()()}[{}][]]])}
(}]}
(([{()}]))[({[{}{}[]]{}})]{((){}{()}){{}}}{}{{[{[][]([])}[()({}())()({[]}{{[[]]([])}})()]]}}
[(([){[](}){){]]}{}([](([[)}[)})[(()[]){})}}]][({[}])}{(({}}{{{{])({]]}[[{{(}}][{)([)]}}
()()[()([{[()][]{}(){()({[]}[(((){(())}))]()){}}}])]
({)}]}[}]{({))}{)]()(](])})][(]{}{({{}[]{][)){}{}))]()}((][{]{]{][{}[)}}{)()][{[{{[[
)}(()[])(}]{{{}[)([})]()}()]}(][}{){}}})}({](){([()({{(){{
}([]]][[){}}[[)}[(}(}]{(}[{}][{}](}]}))]{][[}(({(]}[]{[{){{(}}[){[][{[]{[}}[)]}}]{}}(}
我展示的子测试用例是这个大测试中的第一个......
这是我的java代码:
package Java.Stacks.Hackerrank_Problems;
import java.util.Scanner;
import java.util.Stack;
/**
* Created by BK on 06-08-2017.
*/
public class BalancedParanthesis {
public static void main(String... strings) {
Scanner sc = new Scanner(System.in);
int tc = sc.nextInt();
for (int i = 0; i < tc; i++) {
printAnswer(sc.next());
}
}
private static void printAnswer(String input) {
Stack<Character> stack = new Stack<>();
boolean isValid=true;
for (int i = 0; i < input.length(); i++) {
char currentChar = input.charAt(i);
if (currentChar == '{' || currentChar == '(' || currentChar == '[') stack.push(currentChar);
else if (currentChar == '}') {
if (stack.isEmpty())isValid=false;
else {
if (stack.pop() != '{') {
isValid=false;
}
}
} else if (currentChar == ')') {
if (stack.isEmpty())isValid=false;
else {
if (stack.pop() != '(') {
isValid=false;
}
}
} else if (currentChar == ']') {
if (stack.isEmpty())isValid=false;
else {
if (stack.pop() != '[') {
isValid=false;
}
}
}
}
System.out.println(isValid?"YES":"NO");
}
}
请帮我摆脱这个...谢谢:)
这表示它不起作用...
【问题讨论】:
-
似乎在这里工作正常ideone.com/jOgg4I
-
但它在我的 ide 和hackerrank 中也不起作用......
标签: java algorithm data-structures stack