【发布时间】:2016-07-22 12:51:27
【问题描述】:
我正在尝试实现后缀到中缀和中缀到后缀(使用堆栈)并且一切进展顺利,除了当我从后缀转换时我想不出如何处理括号的想法。它说我必须使用最少数量的括号。例如:
<POSTFIX> ab+c*da-fb-*+
<INFIX> (a+b)*c+(d-a)*(f-b)
<POSTFIX>ab~c+*de-~/
<INFIX>a*(~b+c)/~(d-e)
private static class Postfix {
private void convert(String postfix) {
Stack<String> s = new Stack<>();
for (int i = 0; i < postfix.length(); i++) {
char o = postfix.charAt(i);
if (isOperator(o)) {
if (o == '~') {
String a = s.pop();
s.push(o + a);
}
else {
String b = s.pop();
String a = s.pop();
s.push(a + o + b);
}
} else s.push("" + o);
}
System.out.println("<INF>" + s.pop().toString());
}
}
任何帮助将不胜感激。
【问题讨论】:
标签: java stack parentheses postfix-notation infix-notation