leetcode 150 逆波兰表达式求值(Evaluate Reverse Polish Notation)

今天的题目主要是后缀表达式的运算,是栈的性质的经典例题,然后我今天还是卡克了一下,主要是在char与string的不同卡壳,c++/c中,char是‘*’,而string 以及char[]是“789”;类似的char to int为 int量=atoi(char量),string to int为 int量=stoi(string量),需要包含string容器头文件。

此外,这道题我想起了一道计算器设计题,即根据普通数学表达式(带括号的那种),先转换后缀表达式,再进行计算,我觉得可以在这道题基础上把那个做一下,我找了下是leetcode224. Basic Calculator

https://leetcode.com/problems/basic-calculator/

C++代码如下:

 1 class Solution {
 2 public:
 3     int evalRPN(vector<string>& tokens) {
 4         stack<int> st;
 5         if(tokens.size()==1) return stoi(tokens[0]);
 6         for(int i=0;i<tokens.size();i++){
 7             if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/"){
 8                 int b=st.top();st.pop();
 9                 int a=st.top();st.pop();
10                 int c;
11                 if(tokens[i]=="+") c=a+b;
12                 else if(tokens[i]=="-") c=a-b;
13                 else if(tokens[i]=="*") c=a*b;
14                 else if(tokens[i]=="/") c=a/b;
15                 st.push(c);
16             }else{
17                 int temp=stoi(tokens[i]);
18                 st.push(temp);
19             }
20         }
21         return st.top();
22     }
23 };

猜你喜欢

转载自www.cnblogs.com/joelwang/p/10296703.html