leetcode栈--1、evaluate-reverse-polish-notation(逆波兰表达式)
题目描述
Evaluate the value of an arithmetic expression inReverse 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
解题思路:使用栈结构来存储。遇到数字存入栈中,遇到符号,弹出栈顶的两个元素,进行操作,并将结果放入栈中。
1 class Solution { 2 public: 3 int strtoint(string s) // string转int 4 { 5 int result = 0; 6 int base = 1;//记录属于的位 7 int t = 1;//记录正负号 8 if(s[0] == '-') 9 t = -1; 10 for(int i= s.size() - 1;i>=0;i--) 11 { 12 if(s[i]>='0' && s[i]<='9')//此处一定注意0和9加'' 13 { 14 result += base * (s[i] - '0'); 15 base *= 10; 16 } 17 } 18 return result*t; 19 } 20 int evalRPN(vector<string> &tokens) { 21 int n = tokens.size(); 22 if(tokens.empty() || n<=0) 23 return 0; 24 stack<int> s; 25 for(int i=0;i<n;i++) 26 { 27 if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") 28 { 29 int num2 = s.top();//先弹出的为右操作数 30 s.pop(); 31 int num1 = s.top(); 32 s.pop(); 33 if(tokens[i] == "+") 34 { 35 s.push(num1+num2); 36 } 37 else if(tokens[i] == "-") 38 { 39 s.push(num1-num2); 40 } 41 else if(tokens[i] == "*") 42 { 43 s.push(num1*num2); 44 } 45 else 46 { 47 s.push(num1/num2); 48 } 49 } 50 else 51 { 52 s.push(strtoint(tokens[i])); 53 } 54 } 55 return s.top(); 56 } 57 };