标签:vector eval 除法 leetcode ret str token ble 描述
题目描述链接:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
解题思路:栈的典型应用,并注意减法和除法不满足交换率。
LeetCode C++求解代码:
class Solution { public: stack<string>S; int evalRPN(vector<string>& tokens) { for(int i=0;i<tokens.size();i++){ if(tokens[i]=="+"){ string temp1=S.top(); S.pop(); string temp2=S.top(); S.pop(); int res=std::stoi(temp1)+std::stoi(temp2); string ans=std::to_string(res); S.push(ans); } else if(tokens[i]=="-"){ string temp1=S.top(); S.pop(); string temp2=S.top(); S.pop(); int res=std::stoi(temp2)-std::stoi(temp1); string ans=std::to_string(res); S.push(ans); } else if(tokens[i]=="*"){ string temp1=S.top(); S.pop(); string temp2=S.top(); S.pop(); int res=std::stoi(temp1)*std::stoi(temp2); string ans=std::to_string(res); S.push(ans); } else if(tokens[i]=="/"){ string temp1=S.top(); S.pop(); string temp2=S.top(); S.pop(); int res=std::stoi(temp2)/std::stoi(temp1); string ans=std::to_string(res); S.push(ans); printf("%d",res); } else{ S.push(tokens[i]); } } return std::stoi(S.top()); } };
标签:vector eval 除法 leetcode ret str token ble 描述
原文地址:https://www.cnblogs.com/zzw-/p/13586330.html