美文网首页
[leetcode]evaluate-reverse-polis

[leetcode]evaluate-reverse-polis

作者: 这是朕的江山 | 来源:发表于2016-08-07 22:47 被阅读4次

    Evaluate the value of an arithmetic expression in Reverse Polish Notation.
    Valid operators are+,-,*,/. Each operand may be an integer or another expression.
    Some examples:

    ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
    ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

    答案:

    import java.util.*;
    public class Solution {
        public int evalRPN(String[] tokens) {
            Stack<String> stack = new Stack<String>();  
              
            for(String s : tokens) {  
                if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) {  
                    int second = Integer.parseInt(stack.pop());  
                    int first = Integer.parseInt(stack.pop());  
                    if(s.equals("+")) {  
                        stack.push(String.valueOf(first+second));  
                    } else if(s.equals("-")) {  
                        stack.push(String.valueOf(first-second));  
                    } else if(s.equals("*")) {  
                        stack.push(String.valueOf(first*second));  
                    } else if(s.equals("/")) {  
                        stack.push(String.valueOf(first/second));  
                    }  
                } else {  
                    stack.push(s);  
                }  
            }  
              
            return Integer.parseInt(stack.pop());  
        }
    }
    

    相关文章

      网友评论

          本文标题:[leetcode]evaluate-reverse-polis

          本文链接:https://www.haomeiwen.com/subject/zawlsttx.html