我正在尝试创建一个程序,它以字符串作为参数传递给其构造函数。我需要一个方法来检查字符串是否为平衡的括号表达式。它需要处理 ( { [ ] } ) 中的每个开放符号都需要与其对应的闭合括号配对。例如,用户可以输入 [({})] 这将是平衡的,而 }{ 将是不平衡的。这不需要处理字母或数字。我需要使用栈来完成这个操作。
我得到了这个伪代码,但不知道如何在Java中实现它。任何建议都会很棒。
更新- 抱歉忘记发布我已经做的部分。一开始我使用char,然后我尝试过数组 ... 我不确定该怎么办。
import java.util.*;
public class Expression
{
Scanner in = new Scanner(System.in);
Stack<Integer> stack = new Stack<Integer>();
public boolean check()
{
System.out.println("Please enter your expression.");
String newExp = in.next();
String[] exp = new String[newExp];
for (int i = 0; i < size; i++)
{
char ch = exp.charAt(i);
if (ch == '(' || ch == '[' || ch == '{')
stack.push(i);
else if (ch == ')'|| ch == ']' || ch == '}')
{
//nothing to match with
if(stack.isEmpty())
{
return false;
}
else if(stack.pop() != ch)
{
return false;
}
}
}
if (stack.isEmpty())
{
return true;
}
else
{
return false;
}
}
}
void main(String[] args...) { //在此处编写代码 };
- ppeterka