[SPOJ] ONP – Transform the Expression

原题: http://www.spoj.com/problems/ONP/


题目大意: 一个代数表达式转换成Reverse Polish Notation.


分析: wiki上就有规则. 其实这个题只有三个规则:

  1. 看到(, 忽略
  2. 看到操作符(加减乘除)入栈
  3. 看到), 出栈,打印
  4. 其余直接打印
public class ONP {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
        String s = in.readLine();
        out.printLine(infixToPostfix(s));
    }
    public String infixToPostfix(String infix) {
        Stack<Character> st = new Stack<>();
        StringBuffer sb = new StringBuffer();
        String opt = "+-*/^";
        for (int i = 0; i < infix.length(); i++) {
            Character c = infix.charAt(i);
            if (c.equals('('))
                continue;
            else if (opt.contains(c.toString()))
                st.push(c);
            else if (c.equals(')'))
                sb.append(st.pop());
            else
                sb.append(c);
        }
        return sb.toString();
    }
}