所以我编写了这段代码来确定表达式是否在堆栈中具有平衡括号:
public static boolean isBalanced(String expr) {
StringStack stack = new StringStackRefBased();
try{
for (int i = 0; i<expr.length(); i++){
if (expr.charAt(i) == ('(')){
stack.push("(");
} else if (expr.charAt(i) == (')')){
stack.pop();
}
}
if (stack.isEmpty()){
return true;
} else {
return false;
}
} catch (StringStackException e) {
return false;
}
}
问题是即使表达式具有平衡的括号,堆栈也会继续返回false,因此我的代码出了什么问题?
这是StringStackRefBased的代码
public class StringStackRefBased implements StringStack {
private StringNode head;
public boolean isEmpty(){
return head == null;
}
public void push(String item) throws StringStackException{
head = new StringNode(item);
}
public String pop() throws StringStackException{
String result = null;
if(isEmpty()){
throw new StringStackException("Empty Stack");
}
head.next = head;
return head.toString();
}
public String peek() throws StringStackException{
if (isEmpty()){
throw new StringStackException("Stack underflow");
}
return head.toString();
}
}
答案 0 :(得分:3)
方法很好。如果我使用Java自己的堆栈:
class Main {
public static boolean isBalanced(String expr) {
Stack<String> stack = new Stack<>();
try{
for (int i = 0; i<expr.length(); i++){
if (expr.charAt(i) == ('(')){
stack.push("(");
} else if (expr.charAt(i) == (')')){
stack.pop();
}
}
if (stack.isEmpty()){
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
public static void main(String[] args) {
System.out.println(isBalanced("("));
System.out.println(isBalanced("(()"));
System.out.println(isBalanced("())"));
System.out.println(isBalanced("((()))"));
System.out.println(isBalanced("(()())"));
}
}
将打印:
false false false true true
顺便说一句,你的return语句相当冗长,并且使用异常就是不好的做法。例外只是:例外(例如)。这是IMO更好:
public static boolean isBalanced(String expr) {
Stack<String> stack = new Stack<>();
for (int i = 0; i < expr.length(); i++) {
if (expr.charAt(i) == ('(')){
stack.push("(");
}
else if (expr.charAt(i) == (')')) {
if (stack.isEmpty()) {
return false;
}
stack.pop();
}
}
return stack.isEmpty();
}
这就是你的堆栈如何正常工作:
class StringStack {
private StringNode head = null;
public boolean isEmpty(){
return head == null;
}
public void push(String item) {
StringNode oldHead = head;
head = new StringNode(item);
head.next = oldHead;
}
public String pop() throws StringStackException {
if (isEmpty()) {
throw new StringStackException("Empty Stack");
}
String result = head.item;
head = head.next;
return result;
}
public String peek() throws StringStackException {
if (isEmpty()) {
throw new StringStackException("Stack underflow");
}
return head.item;
}
static class StringNode {
String item;
StringNode next;
public StringNode(String item) {
this.item = item;
}
}
}