日期:2014-05-20 浏览次数:20687 次
//后缀转中缀表达式end为postfix.length()-1,priority参数为1 public static String postToCenter(String[] postfix, int end, int priority) { //判断最后一位是不是数字,是则返回 if (end == 0 || Character.isDigit(postfix[end].charAt(postfix[end].length() - 1))) return postfix[end]; //不是数字就是运算符 StringBuffer buffer = new StringBuffer(); //给每种运算符付一个优先级(+ < - < * </) char s = postfix[end].charAt(0); if (s == '+') s = 2; else if (s == '-') s = 3; else if (s == '*') s = 6; else if (s == '/') s = 7; int k = end - 1; for (int j = 0; k >= 0; k--) { if (Character.isDigit(postfix[k].charAt(postfix[k].length() - 1))) j++; else j--; if (j == 1) break; } if (s < priority) buffer.append('('); buffer.append(postToCenter(postfix, k - 1, s - s % 2)); buffer.append(postfix[end--]); buffer.append(postToCenter(postfix, end, s + s % 2)); if (s < priority) buffer.append(')'); System.out.println(new String(buffer)); return new String(buffer); }
------解决方案--------------------
要理解递归 你得先理解递归