LeetCode 逆波兰表达式java实现

来源:互联网 发布:数据分析相关岗位 编辑:程序博客网 时间:2024/05/29 11:53

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
实现逆波兰算法的关键是查找运算符。
利用栈,将tokens中的元素压入栈,一旦遇到运算符取出两个栈顶元素(取出的同时删除pop())进行运算,将运算所得的结果压入栈内
import java.util.Stack;public class Solution {    public int evalRPN(String[] tokens) {    Stack<Integer> s=new Stack<Integer>();        for (int i=0;i<tokens.length;i++){    if(tokens[i].equals("+")){    int right=s.pop();    int left=s.pop();    int result=left+right;    s.push(result);    }else if(tokens[i].equals("*")){    int right=s.pop();    int left=s.pop();    int result=left*right;    s.push(result);    }else if(tokens[i].equals("-")){    int right=s.pop();    int left=s.pop();    int result=left-right;    s.push(result);    }else if(tokens[i].equals("/")){    int right=s.pop();    int left=s.pop();    int result=left/right;    s.push(result);    }else{    s.push(Integer.parseInt(tokens[i]));    }    }    return s.pop();    }}

0 0
原创粉丝点击