0%

代码随想录第三十一天

字符串-有效的括号

题目链接

这道题多分析一下题目就知道是一种消除题,其实和前面一道题“对对碰”很像,这道题是出现运算符就运算前面两个数字,结果又重新压入栈。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int>st;
for(int i = 0; i < tokens.size(); i++){
if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/"){
int num1 = st.top();
st.pop();
int num2 = st.top();
st.pop();
if(tokens[i] == "+")st.push(num2 + num1);
if(tokens[i] == "-")st.push(num2 - num1);
if(tokens[i] == "*")st.push(num2 * num1);
if(tokens[i] == "/")st.push(num2 / num1);
}
else{
st.push(stoi(tokens[i]));
}
}
return st.top();
}
};
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for item in tokens:
if item not in {"+", "-", "*", "/"}:
stack.append(item)
else:
num1, num2 = stack.pop(), stack.pop()
stack.append(
int(eval(f'{num2} {item} {num1}'))
)
return int(stack.pop())