我有一個方法getRPNString(),它返回Reverse Polish Notation字符串。我想通過空格鍵分割這個字符串來計算它。現在我無法理解如何在我的RNP字符串中添加空格鍵,因爲它不適用於兩位數字。RPN表達式中元素之間的空格java
public class Calc1 {
public static void main(String[] args) {
String in = "((5+3*(4+2)*12)+3)/(1+3)+5";
String out = getRPNString(in);
System.out.println(out);
}
private static String getRPNString(String in) {
LinkedList<Character> oplist = new LinkedList<>();
StringBuilder out = new StringBuilder();
for (int i = 0; i < in.length(); i++) {
char op = in.charAt(i);
if (op == ')') {
while (oplist.getLast() != '(') {
out.append(oplist.removeLast());
}
oplist.removeLast();
}
if (Character.isDigit(op)) {
out.append(op);
/*int j = i + 1;
for (; j < in.length(); j++) {
if (!Character.isDigit(j)) {
break;
}
i++;
}
out.append(in.substring(i, j));*/
}
if (op == '(') {
oplist.add(op);
}
if (isOperator(op)) {
if (oplist.isEmpty()) {
oplist.add(op);
} else {
int priority = getPriority(op);
if (priority > getPriority(oplist.getLast())) {
oplist.add(op);
} else {
while (!oplist.isEmpty()
&& priority <= getPriority(oplist.getLast())) {
out.append(oplist.removeLast());
}
oplist.add(op);
}
}
}
}
while (!oplist.isEmpty()) {
out.append(oplist.removeLast());
}
return out.toString();
}
private static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '%';
}
private static int getPriority(char op) {
switch (op) {
case '*':
case '/':
return 3;
case '+':
case '-':
return 2;
case '(':
return 1;
default:
return -1;
}
}
}
我試圖通過追加(」「)在我的StringBuilder變量進行添加spacebars。但是兩位數字不對。我想我完全不明白如何做到這一點。例如,如果輸入是String in =「((5 + 3 *(4 + 2)* 12)+3)/(1 + 3)+5」;出局將是5342+ + 3 + 13 +/5 +,當我向所有調用添加空格鍵out.append('')** out是** 5 3 4 2 + * 1 2 * + 3 + 1 3 +/5 +,所以像「12」這樣的數字變成了「1 2」。 你能幫忙嗎?
嗨,它的工作原理,謝謝。 – dimads 2015-02-25 12:13:26