牛客 -- leetcode -- evaluate-reverse-polish-notation
生活随笔
收集整理的這篇文章主要介紹了
牛客 -- leetcode -- evaluate-reverse-polish-notation
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目描述
?
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?
最初代碼:
1. 最初沒好好看題,沒注意里面的數(shù)字可能是整數(shù)也可能是表達(dá)式,思考簡單了。一直說越界或者其他。一直想為什么用string,不是char,原來會有表達(dá)式。真的很菜..
2. 理解之后就可以寫了
int evalRPN(vector<string> &tokens) {stack<int> numbers;int n = tokens.size();if(n == 0) return 0;for(int i = 0; i < tokens.size(); i++){if(tokens[i] >= "0" && tokens[i] <= "9"){numbers.push(stoi(tokens[i]));}else{int b = numbers.top();numbers.pop();int a = numbers.top();numbers.pop();int result = 0;if(tokens[i] == "+")result = a + b;else if(tokens[i] == "-")result = a - b;else if(tokens[i] == "*")result = a * b;else if(tokens[i] == "/")result = a / b;numbers.push(result);}}return numbers.top(); }?
?
AC代碼:
class Solution { public:int evalRPN(vector<string> &tokens) {stack<int> numbers;int n = tokens.size();if(n == 0) return 0;for(auto x : tokens){if(x == "+" || x == "-" || x == "*" || x == "/"){if(numbers.size() < 2) return 0;int b = numbers.top();numbers.pop();int a = numbers.top();numbers.pop();if(x == "+") numbers.push(a+b);if(x == "-") numbers.push(a-b); if(x == "*") numbers.push(a*b);if(x == "/") numbers.push(a/b);}else{numbers.push(atoi(x.c_str()));}}return numbers.top();} };?
?
總結(jié)
以上是生活随笔為你收集整理的牛客 -- leetcode -- evaluate-reverse-polish-notation的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 牛客网 -- 计算机历年考研复试上机题
- 下一篇: 牛客 -- leetcode -- ma