下面的代码用于检查给定的字符串是否具有平衡的括号,或者不使用堆栈。
输入“ []”的输出错误。它应该打印true,但是我得到的结果是false。
import java.util.*;
class Solution{
public static void main(String[] argh) {
Scanner sc = new Scanner(System.in);
Stack st = new Stack();
boolean flag = true;
while (sc.hasNext()) {
String input = sc.next();
//Complete the code
for (int i = 0; i < input.length(); i++) {
flag = false;
if ((input.charAt(i) == '{') || (input.charAt(i) == '(') || (input.charAt(i) == '[')) {
st.push(input.charAt(i));
continue;
}
if ((input.charAt(i) == '}') || (input.charAt(i) == ')') || (input.charAt(i) == ']')) {
if (st.isEmpty()) {
flag = false;
} else {
char item = (char) st.pop();
if ((item == '(') && (input.charAt(i) == ')'))
flag = true;
if ((item == '{') && (input.charAt(i) == '}'))
flag = true;
if ((item == '[') && (input.charAt(i) == ']'))
flag = true;
}
}
}
if (!st.isEmpty())
flag = false;
System.out.println(flag);
}
}
}
最佳答案
我在下面复制了您的代码,并进行了一些更改(由注释标识),这些更改应该可以使其正常工作。
import java.util.*;
class Solution{
public static void main(String[] argh) {
Scanner sc = new Scanner(System.in);
Stack st = new Stack();
while (sc.hasNext()) {
// jim - Moved this to inside the loop.
// Assume the input is good unless proven otherwise.
boolean flag = true;
String input = sc.next();
//Complete the code
// jim - Added the "&& flag == true" to exit if the input is bad
for (int i = 0; i < input.length() && flag == true; i++) {
// jim - Commented this out. We'll assume it's good. If the input
// is found to be bad, we set the flag, and the
// "&& flag == true" condition above will exit the loop.
// flag = false;
if ((input.charAt(i) == '{') || (input.charAt(i) == '(') || (input.charAt(i) == '[')) {
st.push(input.charAt(i));
continue;
}
if ((input.charAt(i) == '}') || (input.charAt(i) == ')') || (input.charAt(i) == ']')) {
if (st.isEmpty()) {
flag = false;
} else {
char item = (char) st.pop();
// jim - here, check for not equal, and set to false.
if ((item == '(') && (input.charAt(i) != ')'))
flag = false;
if ((item == '{') && (input.charAt(i) != '}'))
flag = false;
if ((item == '[') && (input.charAt(i) != ']'))
flag = false;
}
}
else {
// jim - added this 'else' clause.
// If there's any character other than [{()}], then it's
// bad input.
flag = false;
}
}
if (!st.isEmpty())
flag = false;
System.out.println(flag);
}
}
}
您可以对代码进行一些改进,但是我记录的一些更改应该可以使它起作用。