Every day a Leetcode
题目来源:150. 逆波兰表达式求值
解法1:栈
用栈模拟逆波兰表示法表示的算术表达式的计算过程。
初始化一个栈 stk。
遍历字符串数组 tokens,根据当前字符串 token 决定操作:
- 若 token 是 1 个算符(“+”、“-”、“*” 或 “/”),取出栈里的前 2 个数字 x 和 y,得到 x+y、y-x、x*y、y/x 其中之一,再压入栈顶。
- 若 token 是数字,将 stoi(token) 压入栈顶。
最终答案为 stk.top()。
代码:
/*
* @lc app=leetcode.cn id=150 lang=cpp
*
* [150] 逆波兰表达式求值
*/
// @lc code=start
class Solution
{
public:
int evalRPN(vector<string> &tokens)
{
stack<int> stk;
for (const string &token : tokens)
{
if (token == "+")
{
int x = stk.top();
stk.pop();
int y = stk.top();
stk.pop();
stk.push(x + y);
}
else if (token == "-")
{
int x = stk.top();
stk.pop();
int y = stk.top();
stk.pop();
stk.push(y - x);
}
else if (token == "*")
{
int x = stk.top();
stk.pop();
int y = stk.top();
stk.pop();
stk.push(x * y);
}
else if (token == "/")
{
int x = stk.top();
stk.pop();
int y = stk.top();
stk.pop();
stk.push(y / x);
}
else
{
int num = stoi(token);
stk.push(num);
}
}
return stk.top();
}
};
// @lc code=end
结果:
复杂度分析:
时间复杂度:O(n),其中 n 是数组 token 的长度。
空间复杂度:O(n),其中 n 是数组 token 的长度。