鏈接:逆波蘭表達式求值_牛客題霸_牛客網
題解:
利用棧,遍歷字符串數組,遇到運算數則入棧,遇到運算符則取出棧頂兩個運算數進行運算,并將運算結果入棧。
class Solution {
public:/*** 代碼中的類名、方法名、參數名已經指定,請勿修改,直接返回方法規定的值即可** * @param tokens string字符串vector * @return int整型*/int evalRPN(vector<string>& tokens) {// write code herestack<int> s;for(auto& c:tokens){if(c=="+"||c=="-"||c=="*"||c=="/"){int y=s.top();s.pop();int x=s.top();s.pop();int ret=0;if(c=="+") ret=x+y;else if(c=="-") ret=x-y;else if(c=="*") ret=x*y;else ret=x/y;s.push(ret);}else {s.push(stoi(c));}}return s.top();}
};