如何将前缀转换为中缀

时间:2016-10-07 00:05:09

标签: java infix-notation

我真的很难理解将Prefix表达式转换为Infix表达式的整个概念。

表达式为Prefix: -4/+1*327,会转换为4-1+3*2/7吗?

另一个例子可能是Prefix: +-a*bc/de,会转换为a-b*c+d/e吗?

是否有某种算法可以使这更简单?

1 个答案:

答案 0 :(得分:1)

试试这个。

public class Prefix {

    static final Map<String, Integer> PREC = new HashMap<>();
    static { PREC.put("+", 1); PREC.put("-", 1); PREC.put("*", 2); PREC.put("/", 2); }

    static class Source {
        final String s;
        Source(String s) { this.s = s; }
        int index = 0;
        String token;
        String next() { return token = index >= s.length() ? null : s.substring(index, ++index); }
    }

    static String parse(String s) { return parse(new Source(s), 0); }

    static String parse(Source t, int prec) {
        Integer self = PREC.get(t.next());
        if (self != null) {
            String op = t.token;
            String result = String.format("%s%s%s",parse(t, self), op, parse(t, self));
            if (self < prec) result = "(" + result + ")";
            return result;
        } else
            return t.token;
    }

    static void test(String prefix) { System.out.println(prefix + " -> " + parse(prefix)); }

    public static void main(String[] args) {
        test("-4/+1*327");
        test("+-a*bc/de");
        test("*-ab+cd");
    }
}

结果:

-4/+1*327 -> 4-(1+3*2)/7
+-a*bc/de -> a-b*c+d/e
*-ab+cd -> (a-b)*(c+d)
相关问题