题解

evaluate-reverse-polish-notation

http://www.nowcoder.com/questionTerminal/22f9d7dd89374b6c8289e44237c70447

巧妙避开对数字字符串的判断

import java.util.*;


public class Solution {
    /**
     * 
     * @param tokens string字符串一维数组 
     * @return int整型
     */
    public int evalRPN (String[] tokens) {
        // write code here
        Stack<Integer> stk = new Stack<>();
        for (int i = 0; i < tokens.length; ++i) {
            String s = tokens[i];
            if (s.equals("+")) {
                int a = stk.pop();
                int b = stk.pop();
                stk.push(a+b);
            }
            else if (s.equals("-")) {
                int a = stk.pop();
                int b = stk.pop();
                stk.push(b-a);
            }
            else if (s.equals("*")) {
                int a = stk.pop();
                int b = stk.pop();
                stk.push(b*a);
            }
            else if (s.equals("/")) {
                int a = stk.pop();
                int b = stk.pop();
                stk.push(b/a);
            }
            else {
                stk.push(Integer.valueOf(s));
            }
        }
        return stk.pop();
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务