LeetCode 150. 逆波兰表达式求值
作者:互联网
题目描述链接: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()); } };
标签:150,cn,int,求值,polish,LeetCode 来源: https://www.cnblogs.com/zzw-/p/13586330.html